8.30.2012

Project Euler Problem 2: Find the sum of the even-valued terms in the Fibonacci sequence

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, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

The answer is 4613732.

First, find all numbers in Fibonacci sequence that is less than 4 million. Then add up all numbers that are even.
List<int> listFibonacci = new List<int> { 1, 2 };
int sum = 0;
int numFibonacci = 0;

while (listFibonacci[listFibonacci.Count - 1] < 4000000)
{
   numFibonacci = listFibonacci[listFibonacci.Count - 1] + listFibonacci[listFibonacci.Count - 2];
   if (numFibonacci < 4000000) listFibonacci.Add(numFibonacci);
      else break;                
}

for (int i = 0; i

No comments:

Post a Comment