Click here to Skip to main content
15,891,033 members
Articles / All Topics

Project Euler Problem #2

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
10 Aug 2011CPOL1 min read 14K   1
Project Euler Problem #2

So these Project Euler problems have become quite addictive. I've actually already completed quite a few of them. However, this post will be devoted to problem number dos.

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.

So this problem is asking us to find all the terms in the Fibonacci sequence that are even and under 4,000,000. Then we have to sum all of those terms.

Alright, first we have to figure out the best way to generate our terms to use. The idea of the sequence is pretty straightforward. We start with two terms, 0 and 1, and then we can use an iterator block to return the second term to an enumerable object. Finally, we can set the second term to itself plus the first and set the first term equal to the new second minus the first.....confusing enough? Yea. Maybe this will help.

C#
public IEnumerable<long> Fibonacci()
{
    long a = 0;
    long b = 1;

    while(true)
    {
        yield return b;

        b = a + b;
        a = b - a;
    }
}

So now we have a Fibonacci generator!

So our final answer can be achieved by using a lambda expression with a 'TakeWhile' extension.

C#
Tools newTools = new Tools();
return newTools.Fibonacci().TakeWhile
(i => i > 4000000).Where(i => newTools.IsEven(i)).Sum();

I have placed my Fibonacci Generator and the IsEven function in a "Tools" class. This will be my common assembly that will be used in each problem's class. I've implemented Dependency Injection in my solution just for the fun of it and will probably go over it in another post sometime. Who knows.

Anyways, for good measure, here is my IsEven function:

C#
public bool IsEven(long number)
{
    return (number % 2 == 0);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Business Analyst
United States United States
Visit my blog, Aimless Technical Babble

Comments and Discussions

 
QuestionProject Euler Pin
farproc200016-Aug-11 3:55
farproc200016-Aug-11 3:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.