偶数斐波纳契数之和<X [英] Sum of Even Fibonacci Numbers < X

查看:52
本文介绍了偶数斐波纳契数之和<X的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究这个问题,我似乎有一个可行的解决方案,但是我很难理解它的行为.

I'm working on this one and I seem to have a working solution but I have difficulty understanding its behaviour.

这就是我所拥有的.

#!/usr/bin/python



def even_fib_sums(limit):
    number = 1
    last = 0
    before_last = 0
    total = 0
    for counter in range (0,limit):
     before_last = last
     last = number
     number = before_last + last
     if not number % 2:
        total += number
        yield total

print sum(even_fib_sums(4000000))

我是编程的新手,但考虑到我需要循环遍历该范围内的所有4000000个数字,这对我来说不是很有效.

I'm new to programming but it makes sense to me that this is not very effective considering I need to cycle through all 4000000 numbers in the range.

如果我使用相同的方法生成多达5个的斐波那契数列,如下所示,您将看到以下结果.

If I use the same approach in generating the Fibonacci sequence up to 5 as follows, you will see the results below.

def generate_fib(limit):
    number = 1
    last = 0
    before_last = 0
    total = 0
    for counter in range (0,limit):
     before_last = last
     last = number
     number = before_last + last
     print number

generate_fib(5)

结果:1​​,2,3,5,8

Result: 1,2,3,5,8

结果中的这些数字中,只有2和8%2 == 0.总和应该是10,但是如果我要使用上面的第一个代码段,我将返回12.为什么这样?

Of these numbers in the result, only 2 and 8 % 2 == 0. The sum should be 10 but I am returning 12 if I am to use the first snippet above. Why so?

推荐答案

通过考虑斐波那契数列中值不超过400万的项,找到偶值项之和.

您只需要循环执行,直到击中的Fib> 400000而不是您的代码试图执行的第4百万斐波那契数字,您可以简化为使用具有sum的生成器函数,仅产生偶数并破坏循环当您击中斐波那契数> 4000000时:

You only need to loop until you hit a fib that is > 400000 not the 4 millionth fibonacci number which your code is trying to do, you can simplify to a using generator function with sum, only yielding even numbers and breaking the loop when you hit a fibonacci number > 4000000:

def fib(n):
    a, b = 0, 1
    while a <= n:
        a, b = b, a + b
        if not b & 1:
            yield b


print(sum(fib(4000000)))

要花费一秒钟的时间来计算:

It takes a fraction of a second to compute:

In [5]: timeit sum(fib(4000000))

100000 loops, best of 3: 6 µs per loop

几分钟后,

尝试将 timet even_fib_sums(4000000)仍在运行.

这篇关于偶数斐波纳契数之和&lt;X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆