Tuesday, June 4, 2013

Finding Fibonicci sequence (C#)

Question


Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Solution


//The method that returns a list of Fibonacci number sequence up to an input number.

public static List Fibonacci(int n)
{
//The first 2 numbers are given and stored in long variables. Add these numbers to the list
long a =1;
long b = 2;

List <int> sequence = new List<int>();

sequence.Add(a);
sequence.Add(b);

int i= sequence.Count;

if (n > 0)
{
while (i< n)
{
long temp = a;
a=b;
b = temp + a;
sequence.Add(b);
i ++ ;
}
}
return sequence;
}

//Calling the method to generate a list of Fibonacci number up to 4000000
Static void Main()
{
int n=4000000;

List list = Fibonacci(n);

//Iterate through the elements of the list and if it is a positive number, keep the sum of the numbers in an long variable and return the sum

int sum =0;

foreach (var v in list)
{
if (v%2 == 0)
{
sum += v;
}
}
Console.WriteLine(sum);
Console.ReadKey();
}

 

2 comments:

Unknown said...

Seems there are some typos in the code:

1. "while (i{" - the while clause is incomplete

2. "new List()" - the list type should be specified

Also, since the Fibonacci uses the last 2 numbers to find the next, I think you could use the sequence.Count and (Count - 1) instead of i.

Prarthana said...

Fixed the typos. Thanks.