用Fibonacci程序求偶数元素的和

2024-04-27 04:03:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

通过考虑Fibonacci序列中值不超过400万的项,求偶数项的和。

到目前为止,我已经能够生成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)

欢迎提出任何建议。在


Tags: 代码元素returnifdef序列建议fibonacci
3条回答

因为这看起来像是家庭作业,所以我加入了一些有趣的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)

您有一个无限循环,因为nwhile循环中从未从零递增。另外,为什么不求和Fibonacci total以及在同一个while循环中找到下一个Fibonacci值,如下所示:

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

输出:

^{pr2}$

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

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)是偶数,那么到^{偶数Fibonacci数的和等于到Fib(n)奇数Fibonacci数的和(因为每个偶数Fibonacci数都是前面两个奇数Fibonacci数的和)。

  3. 直到并包括Fib(n)的所有Fibonacci数(偶数和奇数)的和是Fib(n+2) - 1(通过一个简单的归纳证明)。

所以如果Fib(n)是最后一个包含在和中的偶数,那么 你想要的总数是(Fib(n+2) - 1) / 2。在

相关问题 更多 >