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 [54]:
F=[0,1]  #first 2 terms
f=0   #difine variable additional terms
i=0   #variable selects which terms are added
s=0   #running sum
while f <4000000:
    f=F[0+i]+F[1+i]  #adds previous two terms
    F.append(f)      #adds term to list
    i+=1             #shifts terms so last 2 are added to find f
    if f%2==0:
        s+=f     #if even added to sum
print(s)


4613732

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

In [50]:



0
1
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-50-759202d8f87d> in <module>()
      2 for x in range(33):
      3     print(x)
----> 4     f=F[0+x]+F[1+x]
      5     if f<4000000 and f%2==0:
      6         F.append(f)

IndexError: list index out of range