甚至斐波那契数字总和低于400万 - Python

non*_*ter 1 python math if-statement fibonacci

我在python中尝试第二个Project Euler问题,并想了解为什么我的代码不起作用.

该代码找到了甚至斐波纳契数低于400万的总和

counter = 2
total = 0
while counter <= 4000000:
    if counter % 2 == 0:
        total+= counter    
    counter+= (counter -1)
print total
Run Code Online (Sandbox Code Playgroud)

此代码将输出:2

如果我打印计数器,则输出:4194305

我假设正在执行if语句是一个问题,因为while循环正常运行并且计数器也正确递增.

fre*_*ish 8

问题就在于此counter+= (counter -1).你应该这样做,你把它添加到自己(减1):

a, b = 1, 1
total = 0
while a <= 4000000:
    if a % 2 == 0:
        total += a
    a, b = b, a+b  # the real formula for Fibonacci sequence
print total
Run Code Online (Sandbox Code Playgroud)


jon*_*rpe 8

您的代码计算的系列counter如下:

2 # solid start
3 # good
5 # this is going great
9 # wait, what?
17 # this is going really badly
Run Code Online (Sandbox Code Playgroud)

您不能只是counter - 1每次添加,您需要在系列中添加以前的数字.

那你为什么total这么小?因为奇数减1总是偶数,奇数加偶数总是奇数; 2是你生成的唯一偶数,因此这是你的total.

生成Fibonacci数通常有两个变量做ab,我们开始

a = b = 1
Run Code Online (Sandbox Code Playgroud)

每次迭代看起来像:

a, b = b, a + b
Run Code Online (Sandbox Code Playgroud)