Kibbee.ca
icon
Project Euler: Problem 2

Find the sum of all the even values in the fibonacci sequence that do not exceed 4 million.

[Full Question]

Answer

#define and initialize variables to be used
sumOfEvens = 0
fibValue = 0
p1 = 1
p2 = 1

#Loop until Fibonacci value exceed 4 million
while fibValue  <= 4000000:
    #fibonacci value is the sum of previous 2 values
    fibValue = p1 + p2
    
    #if it is even, add to the sum of even values
    if fibValue % 2 == 0:
        sumOfEvens += fibValue
    
    #store the previous 2 values 
    #so we can solve for the next value
    p1 = p2
    p2 = fibValue

#print sum of evens, which is the answer
print sumOfEvens

[Download Code]

Pretty straight forward for the most part. Go through a loop to find all the fibonacci values, adding the previous 2 numbers, p1 and p2. If the number is even, then add it to the total. Not much interesting here, except that the python tutorial contains basically no information on how to do a while loop.

No Comments Posted