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 [1]:
"""http://codereview.stackexchange.com/questions/9830/python-solution-for-project-euler-2-fibonacci-sums
Collaborated with Aaron Wong
Used this thread as a starting point for this code.
"""
#Creating a function Fib that takes the parameter "limit" which is the largest number you want
def Fib(limit):
#The first two numbers in the Fib sequence and a list to hold the whole sequence
a = 0
b = 1
answer = []
#Loop through b while it is less than the user defined limit
while b < limit-1:
#This creates the Fibonacci sequence as it adds the previous two numbers and then shifts the numbers over one
holder = a
a = b
b+=holder
#Determines if the number is even and if it should be added to the list
if b % 2 == 0:
answer.append(b)
#Sums the list of even numbers
print(sum(answer))
Fib(4000000)
In [20]:
# This cell will be used for grading, leave it at the end of the notebook.
In [74]:
In [ ]: