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.

Solution 1: Brute forcing

By just iterating through all fibonnacci sequence below 4,000,001 (31 iteration) and checking wether even-valued and adding to the variable, we can find the answer.

The python code:

total = 0
pre_f = 1
next_f = 2

while next_f < 4000001: if next_f % 2 == 0: total += next_f
#swaping next_f to pre_f #and making next_f the sum of #pre_f & next_f temp_f2 = next_f next_f = next_f + pre_f pre_f = temp_f2
print(total)

The output: 4613732.
This code run ~0.0.

Solution 2: Improved Iteration

We may not improve the time it took to run but we can reduce the number of iteration from 31 to 11. It takes sum of 2 even numbers or 2 odd numbers to be even. We can see that fibonacci sequence term is even @ terms: 2, 5, 8,11, 14. After two odd valued term we get even valued term.

total = 0
f = 1
even_f = 2

while even_f < 4000001: total += even_f
# finding next even term next_f = f + even_f f = next_f + even_f even_f = next_f + f
print(total)

The output: 4613732.
This code run ~0.0.