我的任务是编写一个程序,对前 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/