【发布时间】:2015-06-18 23:15:39
【问题描述】:
我正在尝试编写一个优化的斐波那契作为能够计算 fib(300) 和 fib(8000) 的作业。这是我目前所拥有的(map 是一个 HashMap)。
public static BigInteger fibMemo(int n) {
if (n <= 1){
return BigInteger.valueOf(n);
}
if (!map.containsKey(n)){
map.put(n, fibMemo(n-1).add(fibMemo(n-2)));
}
return map.get(n);
}
当我打电话时
System.out.println("300: " + FibonacciMemo.fibMemo(300));
就其本身而言,它工作得很好。 还有,
System.out.println("8000: " + FibonacciMemo.fibMemo(8000));
如果我注释掉之前对 fib(300) 的调用,则可以正常工作。但是,如果我保留这两个调用,我会在递归 fibMemo 上得到堆栈溢出。这对我来说似乎很奇怪。有人可以澄清一下情况吗?提前致谢。
代码如下:
import java.util.HashMap; // Import Java's HashMap so we can use it
import java.math.BigInteger;
public class FibonacciMemo {
private static HashMap<Integer, BigInteger> map = new HashMap<Integer, BigInteger>();
/**
* The classic recursive implementation with no memoization. Don't care
* about graceful error catching, we're only interested in performance.
*
* @param n
* @return The nth fibonacci number
*/
public static int fibNoMemo(int n) {
if (n <= 1) {
return n;
}
return fibNoMemo(n - 2) + fibNoMemo(n - 1);
}
/**
* Your optimized recursive implementation with memoization.
* You may assume that n is non-negative.
*
* @param n
* @return The nth fibonacci number
*/
public static BigInteger fibMemo(int n) {
// YOUR CODE HERE
if (n <= 1){
return BigInteger.valueOf(n);
}
if (!map.containsKey(n)){
map.put(n, fibMemo(n-1).add(fibMemo(n-2)));
}
return map.get(n);
}
public static void main(String[] args) {
// Optional testing here
String m = "Fibonacci's real name was Leonardo Pisano Bigollo.";
m += "\n" + "He was the son of a wealthy merchant.\n";
System.out.println(m);
System.out.println("300: " + FibonacciMemo.fibMemo(300));
System.out.println("8000: " + FibonacciMemo.fibMemo(8000));
// 46th Fibonacci = 1,836,311,903
// 47th Fibonacci = 2,971,215,073
}
}
【问题讨论】:
-
地图在哪里声明以及如何声明?
-
你的堆栈跟踪是什么?
-
与
private static HashMap<Integer, BigInteger> map = new HashMap<Integer, BigInteger>();同班 -
我无法复制这个问题——即使只有
fibMemo(8000)而不是两者都有,我也会遇到堆栈溢出。您是否使用-Xss增加了堆栈大小? -
同上,结果与 Neuronaut 相同。 8000 的 StackOverflow,无论是否调用
fib(300)。看来您只是在对抗 Java 的默认堆栈大小。
标签: java stack-overflow biginteger fibonacci