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 [6]:
x1=0 #first value of Fibonacci sequence
x2=1 #second value of Fibonacci sequence
i=0 #initialize i for while loop
num=0 #initialize num for adding even-valued terms
while i<4000001: #runs through i up to 4,000,000
    i=x2 #reset i to the second number in sequence
    if i%2==0: #only selects even numbers and adds them together
        num+=i
    i=x1+x2 #adding the numbers next to each other to get the next number
    x1=x2 #resetting value of x1 to number after previous x1
    x2=i #resetting value of x2 to new number in iteration
print(num)


4613732

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