Euler项目:甚至斐波那契号



fibonacci序列中的每个新项是通过添加前两个项生成的。从1和2开始,前10个术语将是:

1、2、3、5、8、13、21、34、55、89,...

通过考虑斐波那契序列中的术语不超过400万,找到偶数术语的总和。

我的程序打印4613731,但应该是4613732。问题在哪里?

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)
if fib(n) % 2 != 0:
    tot += fib(n)

这检查了奇数,因为偶数mod(%)2为0

另外,您正在计算fib(n)三次。可能想对此做些事情。

谢谢您的答复!我忘记了"什至"的含义,很抱歉浪费时间!我还改进了代码

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)

最新更新