There are tons of algorithms for generating the Fibonacci numbers, such as the recursive way which is quite elegant. However, for this problem only, we don’t need to generate the whole sequence.
Suppose we have already know what and are, it’s easy to calculate . Then we check whether is even or not. If it’s even, we sum the number to the final result. Next we update and , and move to the next item in Fibonacci sequence.
The virtue of this method is to (supposedly) reduce the memory usage. Although there are only 34 Fibonacci numbers under 4 million, and I don’t see a particular reason for avoiding generating all these numbers.
And for your reference, here is the list of first 300 Fibonacci numbers: The first 300 Fibonacci numbers, factored
upper_limit = 4e6 old_fib1 = 1 old_fib2 = 1 new_fib = 0 sum = 2 while(new_fib < upper_limit){ new_fib = old_fib1 + old_fib2 if(new_fib %% 2 == 0){ sum = sum + new_fib } old_fib1 = old_fib2 old_fib2 = new_fib }