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.

For this problem, I begin with the first two entries in the fibonacci sequence. I use those two terms and a while loop to append another term onto the end of our series list. I have a counter, i, that is increased every iteration of the while loop. My counter i helps me specify the index of the previous two entries in series, so that I can add those two entries and append the new value onto series. The while loop also has the condition to execute only when the new term that we would be adding is less that four million. Initially I ran into the problem that the loop would execute one more time than needed because the loop condition was based on the previously created entry. It is important for the loop condition to be based on the value that is going to be appended in order to make sure that the appended value is less than 4 million.

In [1]:
series = [0,1]
i = 0
while series[i]+series[i+1] <= 4000000:
    series.append(series[i]+series[i+1])
    i= i+1
print("Answer: " + str(sum(v for v in series if v % 2.0 == 0)))


Answer: 4613732

I worked with Jessi Pilgram on this problem.


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