12,350,735 members (24,374 online)
Technical Blog
alternative version

11.2K views
Posted

# Project Euler Problem #2

, 10 Aug 2011 CPOL
 Rate this:
CodeProjectSo 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 f

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:
<br />
<br />1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
<br />
<br />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.

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

```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 problems class. I've implemented Dependency Injection on 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:

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

## Share

Visit my blog, Aimless Technical Babble

## You may also be interested in...

 First Prev Next
 Project Euler farproc200016-Aug-11 3:55 farproc2000 16-Aug-11 3:55
 Last Visit: 31-Dec-99 18:00     Last Update: 26-Jun-16 11:53 Refresh 1