快速计算斐波那契数列的方法

Fast way to compute the fibonacci numbers

如果我使用以下方法计算斐波那契数,它将比线性方法更快:

我说得对吗?

方法来自here.

公式:

使用 exponentiation by squaring 您将得到 O(log(n)) 乘法以找到第 n 个斐波那契数。但在这种情况下,乘法不是一个简单的运算,实际时间复杂度为 O(M(n)*log(n)),其中 M(n) 是两个长度为 O(n) 的数字相乘的复杂度。

有多种计算斐波那契数的算法benchmark,包括采用朴素乘法和 Karatsuba 乘法的矩阵方法。

还有一个直接公式 - 斐波那契数列是线性递推关系,n-th 元素有一个已知的精确公式。公式为:

其中 phi 是 golden ratio,psi 是它的倒数。

与矩阵方法一样,这可以在 O(log(n)) 乘法中计算。 phi 的缺点是浮点数,因此您可能会因大数舍入而出错。

P.S。我刚好写了a blog post on the problem. You can also take a look at what wikipedia has to say about it.