## 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;

}

}

}

}

Discussion

As I mentioned in the F# solution, an obvious optimization is to sum as you go.  I’ve also taken it a step further and removed the check for evenness because every third Fibonacci is even.  I layout a rough proof in my comments above.

### 2 responses

9 02 2011

[…] is obviously a port of the C# solution.  The one piece I find interesting […]

11 02 2011

[…] based languages have such similar syntax that this is a copy from the C# solution.  Of course, I had to remove the type declarations because it’s not strongly typed.  […]