Project Euler Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms.

Project Euler Problem 2

Solution

We need the sum of the even Fibonacci numbers not exceeding $4{,}000{,}000$.

The Fibonacci sequence begins:

$$1,2,3,5,8,13,21,34,\dots$$

The even-valued terms are:

$$2,8,34,144,\dots$$

A direct approach is to generate Fibonacci numbers up to $4{,}000{,}000$ and accumulate the even ones.

Python code:

a, b = 1, 2
total = 0

while a <= 4_000_000:
    if a % 2 == 0:
        total += a
    a, b = b, a + b

print(total)

Tracing the computation gives the even Fibonacci terms:

$$2 + 8 + 34 + 144 + 610 + 2584 + 10946 + 46368 + 196418 + 832040 + 3524578$$

Their sum is:

$$4613732$$

Answer: 4613732