我最终得到的可能不是最好的解决方案,但这是我所拥有的(可能将来会帮助某人):
1)我测量了时间,递归方法需要计算第 42 个(例如)斐波那契数。
2)使用迭代的方法,我用递归的方法计算第42个斐波那契数时,计算了执行了多少程序行。(行 = 3*fib_iterative(42)-2)
3) 将 2. 除以 1。我得到了在 1 毫秒内执行的平均行数。
4)使用迭代的方法,我用递归的方法计算第400个斐波那契数时,计算了执行了多少程序行。(行 = 3*fib_iterative(400)-2)
5) 将 4. 除以 3。我得到了 fib_recursive(400) 所花费的估计时间。
// Recursive algorithm, calculates Fibonacci number (slow)
private static double fib_recursive(int n){
if( n <= 2) return 1;
else return fib_recursive(n-1) + fib_recursive(n-2);
}
// Iterative algorithm, calculates Fibonacci number (fast)
private static double fib_iterative(int n){
double a = 1, b = 1;
for (int i = 2; i <= n; i++){
b = a + b;
a = b - a;
}
return a;
}
// Get time, which fib_recursive(int) needs to calculate the 400th Fibonacci number
private static long testRecursiveFor400(){
int elapsedTime = 0;
int start = (int) System.currentTimeMillis();
fib_recursive(42);
elapsedTime = (int) (System.currentTimeMillis() - start);
return (3 * (long) fib_iterative(400) - 2) / ((3 * (int) fib_iterative(42) - 2) / elapsedTime);
}