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, \dots$$
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
This problem can be solved by spotting/proving a recurrence relation between the even Fibonacci numbers, but this requires some work. Instead, I found this problem is more easily solvable by iterating through the Fibonacci sequence and summing the even-valued terms. Ultimately, it is a matter of personal choice and either solution works thanks to the relatively small numbers.
a = 1
b = 2
sum_even_fib = 0
while b <= 4000000:
if b % 2 == 0:
sum_even_fib += b
a, b = b, a + b
print(sum_even_fib)
Explained line by line:
a and b, to 1 and 2 respectively.sum_even_fib to keep track of the sum of even Fibonacci numbers.while loop that continues as long as b (the current Fibonacci number) is less than or equal to four million.b is even using the modulus operator. If it is, we add it to sum_even_fib.a and b to the next two Fibonacci numbers in the sequence.sum_even_fib, which contains the sum of all even Fibonacci numbers not exceeding four million.Running the above code leads to an answer of $4613732$