python - 这是否正常工作 - Python 3 中的斐波那契总和

标签 python numbers sum fibonacci

我的任务是编写一个程序,对前 100 个斐波那契数求和。我检查了 Python 中的输出和 QBasic 64 中的输出,它们并不相同。我也检查了不同的输入。

Input: 10
Output: 89
-----------
Input: 100
Output: 573147844013817084101

正确吗?

这是我的代码:

n = int(input())
print()

p = 0
d = 1
z = p + d

print(str(p) + ' + ' + str(d) + ' = ' + str(z))

for i in range(n - 2):

    p = d
    d = z
    z = p + d
    print(str(p) + ' + ' + str(d) + ' = ' + str(z))

print('Sum:', z)

编辑:代码再次编辑,现在检查。我刚刚在维基百科上找到..这取决于你开始循环的数字。因此,如果我使用 (0, 1, 1, 2, 3, 5, 8, 13, 21 和 34) 作为前 10 个斐波那契数,总和将是 88,而不是 89。

最佳答案

前 10 个和 100 个斐波那契数列的总和分别为 88 和 573147844013817084100:

>>> cache = {}

>>> def fib(n):
        if n == 0: return 0
        if n == 1: return 1
        if not n in cache:
            cache[n] = fib(n - 1) + fib(n - 2)
        return cache[n]

>>> sum([fib(i) for i in range(10)])
88
>>> sum([fib(i) for i in range(100)])
573147844013817084100

关于python - 这是否正常工作 - Python 3 中的斐波那契总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30128330/

相关文章:

python - Flask-SQLAlchemy - SQL 操作

Java - 按四分之一间隔舍入

c# - C# 中的八进制等价物

java - 这些说法有什么区别?

python - 带 numpy 的 Where 子句

c++ - Input String 应该是 Integer - C++

python - 将 Azure Blob 从流附加到 SendGrid 电子邮件

python - c有scanf,python有类似的东西吗?

mysql - Rails sql查询,过滤上千条记录汇总一列

python - 计算未被任何一组区间覆盖的最小正整数