我正在研究Java中的递归Ackermann函数.我在可能的递归线上得到一个错误,23.
Run Code Online (Sandbox Code Playgroud)return Ack(m - 1, Ack(m, n - 1));
非常感谢,如果有人能指出什么是错的.
-Kyle
/*enter code here
Ackerman's function, A(m, n) is defined:
A(0 , n) = n + 1 for n >= 0
A(m , 0) = A(m – 1 , 1) for m > 0
A(m , n) = A(m – 1 , A(m , n - 1)) for n >= 0
*/
public class AckFun {
public static int Ack(int m, int n) {
if (m == 0) {
return 2 * n;
} else if (m >= 1) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 2;
} else {
return Ack(m - 1, Ack(m, n - 1));
}
}
return n; // Not sure what to return here, Eclipse suggested this.
}
public static void main(String args[]) {
System.out.println(Ack(3, 4));
}
}
Run Code Online (Sandbox Code Playgroud)
你需要让你的堆叠更大:
http://thilinamb.wordpress.com/2008/12/22/how-to-increase-the-java-stack-size/
使用较大的堆栈,它运行时没有stackoverflow,但给出0.
编辑:你的代码是错误的,这就是它给出错误的原因.尝试完全按照定义所说的重写代码:
//I assume that you check that n and m are non-negative before you run this
if (m == 0) {
return n + 1;
} else if (n == 0) {
return Ack(m - 1, 1);
} else {
return Ack(m - 1, Ack(m, n - 1));
}
Run Code Online (Sandbox Code Playgroud)
PS.不要责怪我发布家庭作业问题的源代码.我相信学习编程的最好方法是阅读和理解别人的代码.