## Project Euler 002 – C#

8 02 2011

Problem 2

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.

Solution

namespace ProjectEulerCSharp_002

{

//By considering the terms in the Fibonacci sequence

//whose values do not exceed four million, find the

//sum of the even valued terms.

class Program

{

static void Main(string[] args)

{

//typically when calculating fibonacci series

//it’s performed two elements at a time

//this is not a requirement

int fib0 = 1;

int fib1 = 1;

int fib2 = 2;

while (fib2 < 4000000)

{

//we know the fib2

//is always even

//and represents ALL

//evens in the series

//see the ‘proof’ below

//odd + even = odd

fib0 = fib1 + fib2;

//odd + even = odd

fib1 = fib0 + fib2;

//odd + odd = even

fib2 = fib0 + fib1;

}