#!/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:
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
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.
0 + 1 + 3 + 8 + 21 + 55 + 144 + 377 + 987 = 1596.
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".
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With