Friday, June 19, 2015

Euler problem 2

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.

Answer 

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 es preceded by 2 odd fib 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 (I wont prove this because is not part of the question).

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:


long fibCalculation ( 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 fib = 0 ;
   
while ( ( fib = fibCalculation ( nearest -- , golden ) ) % 2 || fib > number ) ;
   
   
return ( fibCalculation ( nearest + 3 , golden ) - 1 ) / 2 ;
}

No comments:

Post a Comment