Advertisement
ntodorova

07_Fibonacci

Nov 19th, 2012
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.75 KB | None | 0 0
  1. using System;
  2. using System.Numerics;
  3.  
  4. /*
  5.  * 7. Write a program that reads a number N and calculates the sum of the first N members
  6.  * of the sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, …
  7.  */
  8. class Fibonacci
  9. {
  10.     static void Main()
  11.     {
  12.         int n;
  13.         BigInteger first = 0;
  14.         BigInteger second = 1;
  15.         BigInteger tmp = 0;
  16.         BigInteger sum = 0;
  17.  
  18.         Console.Write("N = ");
  19.         string strN = Console.ReadLine();
  20.  
  21.         if (!int.TryParse(strN, out n))
  22.         {
  23.             Console.WriteLine("Invalid number: {0}", strN);
  24.         }
  25.         else
  26.         {
  27.             for (int i = 0; i < n; i++)
  28.             {
  29.                 tmp = first;
  30.                 first = second;
  31.                 second += tmp;
  32.  
  33.                 sum += tmp;
  34.             }
  35.  
  36.             Console.WriteLine("The sum of the element to N is {0}.", sum);
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement