11
\$\begingroup\$

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.

\$\endgroup\$
12
\$\begingroup\$

If you dig a little deeper in the math, it is very straightforward to realize that every third Fibonacci number can be computed with the formula:

\$F_{n+6} = 4 F_{n+3} + F_{n}\$

You can reuse your function if you work the recursion backwards a couple of steps, and do something like:

private static IEnumerable<int> GetEvenFibonacciNumbers()
{
    var first = 2;
    var second = 0;
    while (true)
    {
        var nextFibonacciNumber = first + 4*second;
        yield return nextFibonacciNumber;

        first = second;
        second = nextFibonacciNumber;
    }
} 

This will not only make your code ~3x faster, but will render your other functions trivial to write.

\$\endgroup\$
11
\$\begingroup\$

I think using more LINQ will benefit both readability and conciseness.

The Where method has an overload where the predicate function gets fed the index too, the type is:

public static IEnumerable<TSource> Where<TSource>( 
    this IEnumerable<TSource> source, 
    Func<TSource, int, bool> predicate 
)

So the code can become just:

public static int Solve()
{
  return FibonacciNumbers()
           .TakeWhile(i => i < upperLimit)
           .Where( (_, i) => i % 3 == 0)
           .Sum()
}

I also removed Get from the name of the function generating fibonacci numbers, as get has very precise meaning in OOP and using it when you do not mean that is confusing.

\$\endgroup\$
1
\$\begingroup\$

I just wanted to offer an alternative answer to your implementation that I discovered after trying to come up with a cool way to do Euler's #2.

The algorithm uses an equation I discovered: Fib(x+3) = 4*Fib(x) + Fib(x-3) (this works for x > 3, otherwise assume Fib(x-3) is 0).

Due to the nature of the fibonacci sequence we know that every 3rd fibonacci number is even. The equation above only uses every 3rd fibonacci... which means we can calculate all even fibonacci numbers without calculating the odds one at all.

Here's the code:

int fib = 2, sum = 0, holder = 0;
while (fib < 4000000)
{
    sum += fib;
    int swapper = fib;
    fib = 4 * fib + holder;
    holder = swapper;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.