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.

First, I created two variables a and b, which represent the first two numbers of the Fibonacci sequence. I got the idea to format it this way from a stackoverflow article, as using the syntax: a = 0 b = 1 would later give me strange answers.


In [124]:
a, b = 0, 1

Then I created an empty list to hold all the terms below four million of my Fibonacci sequence.


In [125]:
fib = []

I then used a while loop to append Fibonacci terms into my list which would continue to run until a term reached the value of 4000000. I also updated the values of the next two terms in the sequence according to the definition of the Fibonacci sequence.


In [126]:
while b <= 4000000:
    a, b = b, a + b
    fib.append(b)

I then created a new variable, total, and set it to zero.


In [127]:
total = 0

Using a for loop, I looped through all the terms in my list of Fibonnacci numbers, and if it was even (evenly divisible by two), I added it to the total.


In [128]:
for n in fib:
    if n % 2 == 0:
        total += n

Finally I printed the total, which is the sum of the even-valued terms in the Fibonacci sequence whose highest value doesn't exceed four million.


In [129]:
print(total)


4613732

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