我的回答是针对linear recurrence sequences 的一个通用解决方案。您需要一些基本的代数知识才能完全理解它。
让我们有一个向量
然后我们将它与矩阵相乘
我们会收到:
因此,当我们将向量与该矩阵相乘时,我们会得到下一个斐波那契数。但是如果我们将向量乘以 T2 会发生什么?
这样,我们在下一个(第(n+3)个)之后构造了斐波那契数。现在,如果我们从这个向量中的前两个斐波那契数开始并乘以 Tn-1,我们会得到什么?
因此,通过将我们的向量与矩阵 T 相乘,提高到 (n-1) 次方,我们可以得到第 n 个斐波那契数。我们可以通过exponentiation by squaring 在 O(log n) 时间内计算 Tn-1。当然,我们应该通过模 108 + 7 进行所有计算。
这是我的实现链接(Java 中):http://pastie.org/8519742
这个算法应该适用于 n 的所有正值,直到 2108。
该方法的示例运行时间(使用与 Peter Lawrey 的 answer 相同的时间测量):
fib(1,000,000,000,000,000,000) is 8,465,404 took us 1022.8 to calculate
fib(100,000,000,000,000,000) is 60,687,801 took us 325.7 to calculate
fib(10,000,000,000,000,000) is 9,115,009 took us 247.2 to calculate
fib(1,000,000,000,000,000) is 8,361,917 took us 233.3 to calculate
fib(100,000,000,000,000) is 11,279,600 took us 218.3 to calculate
fib(10,000,000,000,000) is 72,758,000 took us 6027.7 to calculate
fib(1,000,000,000,000) is 82,461,898 took us 184.2 to calculate
fib(100,000,000,000) is 60,584,292 took us 180.4 to calculate
fib(10,000,000,000) is 68,453,509 took us 162.0 to calculate
fib(1,000,000,000) is 90,703,191 took us 145.4 to calculate
fib(100,000,000) is 21 took us 131.3 to calculate
fib(10,000,000) is 60,722,758 took us 112.0 to calculate
fib(1,000,000) is 72,117,251 took us 99.8 to calculate
fib(100,000) is 33,178,829 took us 92.3 to calculate
fib(10,000) is 49,520,320 took us 70.8 to calculate
fib(1,000) is 95,802,669 took us 60.1 to calculate
fib(100) is 24,278,230 took us 39.3 to calculate
fib(10) is 55 took us 27.0 to calculate
fib(1) is 1 took us 16.3 to calculate
但是,尽管如此,这不是解决您的问题的最快算法。众所周知,斐波那契数在某些模块下具有周期性残差。在斐波那契数字上引用the wikipedia entry:
可以看出,如果斐波那契数列的成员取 mod n,则所得数列必须是周期最多为 n2-1 的周期。
换句话说,如果您找到这个周期(例如,tortoise and hare algorithm - 线性复杂度),您还可以找到 every 斐波那契数模 108+7。