Problem 2

Problem 2#

from project_euler import get_problem_description

get_problem_description(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, \dots$$

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Let’s begin by creating a generator which will create our fibonacci numbers

def fibonacci():
    first_term = 1
    yield first_term
    second_term = 2
    yield second_term
    while True:
        next_term = first_term + second_term
        yield next_term
        first_term = second_term
        second_term = next_term

Let’s try it out.

f = fibonacci()
[next(f) for _ in range(10)]
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Looks like our numbers match! Now let’s see if we can solve the problem.

total = 0
f = fibonacci()
while num := next(f):
    if num < 4e6 and num % 2 == 0:
        total += num
    if num > 4e6:
        break

print(total)
4613732

And our result looks correct!