Skip to content
Advertisement

Finding the sum of even valued terms in Fibonacci sequence

#!/usr/bin/python2

"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
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.
"""

odd, even = 0,1
total = 0
while True:
    odd = odd + even  #Odd
    even = odd + even     #Even
    if even < 4000000:
        total += even
    else:
        break
print total

My algo:

  1. If I take first 2 numbers as 0, 1; the number that I find first in while loop will be an odd number and first of Fibonacci series.
  2. This way I calculate the even number and each time add the value of even to total.
  3. If value of even is greater than 4e6, I break from the infinite loop.

I have tried so much but my answer is always wrong. Googling says the answer should be 4613732 but I always seem to get 5702886

Advertisement

Answer

Basically what you’re doing here is adding every second element of the fibonacci sequence while the question asks to only sum the even elements.

What you should do instead is just iterate over all the fibonacci values below 4000000 and do a if value % 2 == 0: total += value. The % is the remainder on division operator, if the remainder when dividing by 2 equals 0 then the number is even.

E.g.:

prev, cur = 0, 1
total = 0
while True:
    prev, cur = cur, prev + cur
    if cur >= 4000000:
        break
    if cur % 2 == 0:
        total += cur
print(total)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement