After I have tackled the first problem I come to Project Euler Problem 2 which states
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.
If we take into account that
- adding 2 odd numbers will result in an even number
- adding an odd to an even number will result in an odd number
we only need to take every third term.
But before we can get there we need to get all the fibonacci numbers like so
private static IEnumerable<int> GetFibonacciNumbers()
{
var first = 0;
var second = 1;
while (true)
{
var nextFibonacciNumber = first + second;
yield return nextFibonacciNumber;
first = second;
second = nextFibonacciNumber;
}
}
which will generate infinite terms of the fibonacci numbers. We will then restrict this by using the TakeWhile()
extension method.
Getting only the even terms up to a specific limit can be achieved by
private static IEnumerable<int> GetEvenFibonacciNumbersTill(int upperLimit)
{
var counter = 0;
foreach (var currentTerm in GetFibonacciNumbers().TakeWhile(i => i < upperLimit))
{
counter++;
if (counter == 3) // every third term is even
{
yield return currentTerm;
counter = 0;
}
}
}
which is called by the int Solve()
method like so
private static readonly int fourMillions = 4000000;
public static int Solve()
{
return GetEvenFibonacciNumbersTill(fourMillions).Sum();
}
As usual any improvements in style, performance, naming or memory usage are welcome.