-2

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.

My program prints 4613731, but it is supposed to be 4613732. Where is the problem?

def fib(n):
    if n == 0:
        return 1
    elif n == 1:
        return 2
    else:
        return fib(n-1)+fib(n-2)

tot = 0
n = 0
while fib(n) <= 4000000:
    if fib(n) % 2 != 0:
        tot += fib(n)
    n += 1

print(tot, n)

2 Answers2

1
if fib(n) % 2 != 0:
    tot += fib(n)

This checks for odd values, since an even mod (%) 2 is 0

Also, you're calculating fib(n) three times. Might wanna do something about that.

ubadub
  • 3,571
  • 21
  • 32
1

Thank you for the reply! I forgot what 'even' meant, sorry for wasting your time! I also improved my code,

tot = 0
a = 1
b = 1
h = 0

while h <= 4000000:
    if h % 2 == 0:
        tot += h
    a = b
    b = h
    h = a + b

print(tot)