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).

Advertisements

Actions

Information

2 responses

9 02 2011
Project Euler 002 – IronRuby «

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

11 02 2011
Project Euler 002 – JavaScript «

[…] 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.  […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: