Hello I have been trying to do the opposite of project Euler question 2 (which is to sum of all even Fibonacci numbers less than 4,000,000). I am trying to print the sum of all odd Fibonacci numbers less than 2,000,000 however I cannot seem to get the correct answer. This is the code I have so far
fib1 = 1
fib2 = 2
fibholder = 0 #place holder for the new value
Sum = 0
while fibholder<2000000:
fibholder = fib1 + fib2
if fibholder%2==1:
Sum+=fibholder
fib1 = fib2
fib2 = fibholder
print(Sum)
You are skipping the first two odd numbers in the sequence and including the first odd value greater than 2,000,000 in your sum because you calculate the next fibonacci number and increment your total before your while loop checks whether or not the value is less than your limit. You could correct your existing approach by initializing your variables to include the beginning of the sequence and by moving your calculation of the next number in the sequence to the end of your while loop.
total = 1
fib1 = 0
fib2 = 1
fibholder = fib1 + fib2
while fibholder < 2000000:
if fibholder % 2:
total += fibholder
fib1 = fib2
fib2 = fibholder
fibholder = fib1 + fib2
print(total)
# 2435423
That said, the logic might be easier to follow if you just generate the odd fibonacci numbers and then handle the sum.
def odd_fibonacci(limit):
a, b = 0, 1
while a < limit:
if a % 2:
yield a
a, b = b, a + b
x = sum(n for n in odd_fibonacci(2000000))
print(x)
# 2435423
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加