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]:
"""first few numbers : 0 1 1 2 3 5 8 13..."""

a=1
b=0
c=0
i=0
mylist=[0]

while (a<=4000000):
    c=a+b #c is the value of the sum of the previous two terms. 
    b=a   #b then becomes the term that was in front of it, a.
    a=c   # a then becomes c
    if a%2==0: #even
            mylist[i]=a
            mylist.append(a)
            i+=1 #goes to next element on the list
            
print(mylist) # THIS IS THE LIST OF ALL THE EVEN NUMBERS! not too sure why 3524578 appears twice,

del mylist[11] # so it is deleted here.
print(mylist)
answer = sum(mylist)
print(answer) # The answer is 4613732!


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

In [ ]:


In [ ]:


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

In [ ]:


In [ ]: