Project Euler problem 2 This is a question about Project Euler number 2, a relatively easy one. The question is: 


  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.


My code is pretty simple; I'm interested in other ways of doing it (lamdba expressions for instance). 

namespace ProjectEuler
{
    public class Fibonacci
    {
        // find even number fibonacci terms &lt; 4 mil.
        public void FibonacciSequence(int limit)
        {
            var sw = Stopwatch.StartNew();
            int a = 0;
            int b = 1;
            int total = 0;
            int evenTerms = 0;

            while (total &lt; limit)
            {
                total = a + b;
                a = b;
                b = total;
                if (total % 2 == 0)
                {
                    evenTerms += total;
                }                
            }
            sw.Stop();
            Console.WriteLine(evenTerms);
            Console.WriteLine(sw.ElapsedMilliseconds);
        }
    }
}
This is the solution I came up with using the Fibonacci succession closed form:



that uses the golden radio:

 

First we can see that for any even Fibonacci number the sum of all the previous even and odd Fibonacci is equal.

Each even Fibonacci number is preceded by 2 odd Fibonacci numbers. 

o o e o o e

1 1 2 3 5 8....

This means that we can transform each of the even Fibonacci in the sum of the 2 previous odd Fibonacci .

So n being any even Fibonacci and f(n) the sum of all even Fibonacci up to n we have:



Also the sum of all Fibonacci numbers up to fib(x) is equal to fib(x+2)-1.

So given any number f we find x by calculating the closest Fibonacci  number fib(x) that is even and less than or equal to f. We then can finally compute  fib(x+2)-1.

The code (this is C++ but it can easily be translated to C#):

long fib ( int i, double golden )
{
    return pow ( golden, i ) / sqrt ( 5 ) + 0.5 ;
}


long findSumEvenFibUpto ( int number )
{
    const double golden = ( 1 + sqrt ( 5 ) ) / 2 ;
    long nearest = round ( log ( sqrt ( 5 ) * number ) / log ( golden ) );

    int fibo = 0 ;
    while ( ( fibo = fib( nearest -- , golden ) ) % 2 || fibo &gt; number ) ;

    return ( fib ( nearest + 3 , golden ) - 1 ) / 2 ;
}