Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 791
yetanotherstacker Avatar asked Jan 29 '12 13:01

yetanotherstacker


People also ask

What are the even numbers in Fibonacci sequence?

The even number Fibonacci sequence is, 0, 2, 8, 34, 144, 610, 2584…. We need to find n'th number in this sequence. If we take a closer look at Fibonacci sequence, we can notice that every third number in sequence is even and the sequence of even numbers follow following recursive formula.

What is the sum of the first three even indexed Fibonacci sequence?

0 + 1 + 3 + 8 + 21 + 55 + 144 + 377 + 987 = 1596.

How do you find the number of terms in the Fibonacci sequence?

Any Fibonacci number can be calculated using the golden ratio, Fn =(Φn - (1-Φ)n)/√5, Here φ is the golden ratio and Φ ≈ 1.618034. 2) The ratio of successive Fibonacci numbers is called the "golden ratio".

What is the sum of the first terms of Fibonacci sequence?

The list of Fibonacci numbers is given as 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. On summation of numbers in the sequence, we get, Sum = 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 = 88. Thus, the sum of the first ten Fibonacci numbers is 88.


1 Answers

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)
like image 76
Rob Wouters Avatar answered Oct 18 '22 04:10

Rob Wouters