使用Fibonacci程序求和偶数元素

时间:2015-04-01 15:28:52

标签: python sequence fibonacci

我正在尝试使用Python解决以下问题:

Fibonacci序列中的每个新术语都是通过添加前两个术语生成的。从1和2开始,前10个术语将是: 1,2,3,5,8,13,21,34,55,89,......

通过考虑Fibonacci序列中的值不超过四百万的项,找到偶数值项的总和。

到目前为止,我已经能够生成Fibonacci元素,但在尝试对偶数元素求和时,我的代码似乎停滞不前。以下是代码:

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

n=0
total=0

while fib(n)<=4000000:
    if fib(n)%2==0:
        total+=fib(n)

print(total)

欢迎任何建议。

4 个答案:

答案 0 :(得分:4)

你有一个无限循环,因为n循环中while从零增加。另外,为什么不总和你的Fibonacci总以及在同一个while循环中找到下一个Fibonacci值,如下所示:

x= 1
y=1
total = 0
while x <= 4000000:
    if x % 2 == 0:
        total += x
    x, y = y, x + y     
print (total)

<强>输出:

4613732

答案 1 :(得分:1)

因为这看起来像是家庭作业,所以我投入了一些有趣的Python

from math import sqrt
# Using Binet's formula
def fib(n):
    return int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)))

def sum_even_terms(limit = 4000000):
    n = total = 0
    while True:
        term = fib(n)
        n += 1
        if term > limit: break 
        if term % 2 == 0:
            total += term
    return total

print sum_even_terms()

def is_nth_term_even(n):
    return (fib(n) % 2 == 0)

print is_nth_term_even(30)

答案 2 :(得分:1)

只是为了好玩,这是一个非常简短的解决方案:

def fib_even_sum(limit=4*10**6):
    """Sum of the even Fibonacci numbers up to the given limit."""
    b, c = 1, 2
    while c <= limit:
        a = b + c; b = c + a; c = a + b
    return b // 2

print fib_even_sum()  # outputs 4613732

它基于以下事实:

  1. 每三个斐波纳契数都是偶数。

  2. 如果Fib(n)是偶数,那么偶数斐波纳契数到[{1}}的总和等于奇数的总和 Fibonacci数最多为Fib(n)(因为每个偶数Fibonacci数是前两个奇数Fibonacci数的总和)。

  3. 所有Fibonacci数字(偶数和奇数)的总和为Fib(n)Fib(n)(通过归纳的简单证明)。

  4. 因此,如果Fib(n+2) - 1是要包含在总和中的最后一个偶数,那么 你想要的总数只是Fib(n)

答案 3 :(得分:0)

您也可以使用生成器并添加数字

def fib():
    a, b = 0, 1
    while 1:
        yield a
        a, b = b, a + b

f = fib()
total = 0
while total <= 4000000:
    current =  f.next()
    if current % 2 == 0:
        total += current

print total