Here's an alternate direct method
It relies on a few properties:
- Each Fibonacci number can be calculated directly as floor( pow( phi, n ) + 0.5 ) (See Computation by Rounding in http://en.wikipedia.org/wiki/Fibonacci_number ). Conversely the index of the biggest Fibonacci number less than i is given by floor( log(i*sqrt(5)) / log(phi) )
- The sum of the first N Fibonacci numbers is the N+2th fibonacci number minus 1 (See Second Identity on the same wikipedia page)
- The even Fibonacci numbers are 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 upto the same point in the sequence.
Point 4 can be seen from this:
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 convert our maximum value of 4000000 calculate the index of the highest Fibonacci number
less than it.
int n = floor(log(4000000*sqrt(5))/log(phi)); // ( = 33)
33 is divisible by 3 so it is an even Fibonacci number, if it wasn't we'd need to adjust n like this.
n = (n/3)*3;
The sum of all Fibonacci numbers up to this point if given by
sum = floor( pow( phi, n+2 ) + 0.5 ) - 1; // ( = 9227464 )
The sum of all even numbers is half of this:
sum_even = sum/2; // ( = 4613732 )
Nice thing about this is that its an O(1) (or O(log(N)) if you include the cost of pow/log) algorithm, and works on doubles.. so we can calculate the sum for very large values.
NOTE: I edited and moved this answer from a closed duplicate of this question. http://stackoverflow.com/questions/3270863