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)

        {

            int answer = 0;

            //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

                answer += fib2;

 

                //odd + even = odd

                fib0 = fib1 + fib2;

                //odd + even = odd

                fib1 = fib0 + fib2;

                //odd + odd = even

                fib2 = fib0 + fib1;

            }

 

            System.Console.WriteLine(answer);

        }

    }

}

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.

If you have questions, leave a comment or please find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).