python - 让fibo更快

标签 python fibonacci

<分区>

我需要编写一个代码来提供一个数字并向我打印 F[number]。这段代码非常慢。有什么关于更快代码的想法吗?

 while True:
      n=input()
      if n=='END' or n=='end':
         break
      class Fibonacci:
            def fibo(self, n):
                if int(n) == 0:
                   return 0
                elif int(n) == 1:
                   return 1
                else:
                  return self.fibo(int(n)-1) + self.fibo(int(n)-2)
      f=Fibonacci()
      print(f.fibo(n))

最佳答案

我在这篇文章中写了一些关于更快斐波那契的内容,也许其中一个对您有用? https://sloperium.github.io/calculating-the-last-digits-of-large-fibonacci-numbers.html

无论如何。您的代码非常慢,因为您的运行时间呈指数级增长,一遍又一遍地调用相同的子树。

您可以尝试线性解决方案:

def fib3(n):
    if n == 0:
        return 0
    f1 = 0
    f2 = 1

    for i in range(n-1):
        f1,f2 = f2, f1+f2
    return f2

关于python - 让fibo更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53564652/

相关文章:

javascript - Javascript 数组中偶数的总和?

python - 递归斐波那契函数是如何推导出来的?

clojure - 为什么减少这个惰性序列会使这个 Clojure 程序减慢 20 倍?

lisp - 解决斐波那契数列的 lisp-way

python - 重复索引列表

python - 在图中追逐(有点)未知点的算法

python - 不透明度的 QVariantAnimation : the item appears at the end of the animation

python - 将值附加到字典列表

python - (Django) 在模型中定义 `__str__` ,而其他模型的属性尚未定义

c++ - 如何将递归转换为迭代解决方案