Learning Java Recursion, Ackerman function
java, recursion
Solution
You need to make your stack larger:
http://thilinamb.wordpress.com/2008/12/22/how-to-increase-the-java-stack-size/
With larger stack it runs without stackoverflow, but gives 0.
EDIT: Your code is wrong, that is why it gives the error. Try to rewrite the code exactly as the definition says:
//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));
}
PS. Don't blame me for posting source code for homework problems. I believe that the best way to learn programming is by reading and understanding someone else's code.
Problem
I'm working on a recursive Ackermann function in Java. I am getting an error at may recursive line, 23. ``` return Ack(m - 1, Ack(m, n - 1)); ``` Thanks so much if anyone could point out what's wrong. -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)); } } ```