Here's an alternative direct method. It relies on several properties:
- Each Fibonacci number can be calculated directly as a gender (pow (phi, n) + 0.5) (See "Calculation by Rounding" at http://en.wikipedia.org/wiki/Fibonacci_number ). Conversely, the index of the largest Fibonacci number smaller than i is determined by gender (log (i * sqrt (5)) / log (phi))
- The sum of the first Fibonacci numbers N is the N + 2nd Fibonacci number minus 1 (see The second certificate on the same wikipedia page).
- Even Fibonacci numbers are every third number. (Look at the sequence mod 2, and the result is trivial)
- The sum of the even Fibonacci numbers is half the sum of the odd Fibonacci numbers to the same point in the sequence.
From this you can see point 4:
Sum of first 3N fibonacci numbers =(F(1) + F(2))+ F(3) +(F(4) + F(5))+ F(6) + ... +(F(3N-2) + F(3N-1))+ F(3N) = F(3) + F(3) + F(6) + F(6) + ... + F(3N) + F(3N) = 2( F(3) + F(6) + ... + F(3N) ) = 2 ( Sum of odd fibonacci numbers up to F(3N) )
So, we convert our maximum value of 4,000,000 to calculate the index of the highest Fibonacci number than it is.
int n = floor(log(4000000*sqrt(5))/log(phi));
33 is divided by 3, so this is an even Fibonacci number, if there was no need to adjust n.
n = (n/3)*3;
The sum of all Fibonacci numbers to this point, if given
sum = floor( pow( phi, n+2 ) + 0.5 ) - 1;
The sum of all even numbers is half this:
sum_even = sum/2; // ( = 4613732 )
The nice thing is that its O (1) (or O (log (N)), if you include the cost of the pow / log algorithm), and works at doubling .., so we can calculate the sum for very large values.
NOTE. I edited and moved this answer from a closed duplicate of this question. Fibonacci less than 4 million
Michael anderson
source share