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 [2]:
def is_even_sum(x): #created this funtion at Dr. Granger's suggestion rather than having it in fibonnaci function
    even=0          #starts sum at 0
    for i in x:     #iterates through numbers and if number is even adds to total
        if i%2==0:
            even+=i
    return even      #returns the total of even numbers

In [3]:
print(is_even_sum([1,2,3,4,5,]))     #test for is even function


6

In [10]:
def fibonacci(x,y): #Decides what numbers to start the Fibonnaci sequence at- i.e 0,1
    fibona=[x,y]    #starts list with the numbers of choosing
    fib=0           #assigns fib so it can be referenced later (could be any number under 4 million I chose 0)
    while fib < 4*10**6:
        fib=x+y     #reassigns fib
        x=y 
        y=fib   #reassigns x and y
        if fib < 4*10**6:  ##Without this statement function returns a number that is one iteration past the limit
            fibona.append(fib)#however without it the sum is unaffected for this problem because it is an odd number
    return fibona

Below tests that numbers in fibona don't exceed four million. The final number did exceed four million untill I added the if statement in fibonacci(). This was because fib stored the previous number and as long as that was under 4 million it would still assign and append one more value of fib.


In [11]:
print( fibonacci(0,1))


[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578]

In [9]:
print(is_even_sum((fibonacci(0,1)))) #sums the even values in series created by fibonacci()


4613732

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