Project Euler: Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 0 and 1, the first 12 terms will be:

0, 1, 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.


In [5]:
a = 0
b = 1
fib_max = 0
fib_list = [a, b]
while fib_max <= 4000000:
    fib_max = a + b
    if fib_max < 4000000:
        fib_list.append(fib_max)
    a = b
    b = fib_max
print(fib_list)


[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578]

In [6]:
even_fib = [x for x in fib_list if x % 2 == 0]
print(even_fib)


[0, 2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]

In [7]:
print(sum(even_fib))


4613732

In [ ]:
# This cell will be used for grading, leave it at the end of the notebook.