Originally Posted by
gonfreecks
i cant really understand this concept
i have this code...
public static int A(int m, int n){
if(m == 0) return n+1;
else if(m > 0 && n ==0) return A(m-1,1);
else if(m > 0 && n > 0) return A(m-1, A(m, n-1);
return 0;
}
my code works but i dont really understand what it does,
see i called this method with 3,4 and it spits out 125 as it should
but w/ 4,3 the machine runs out of stack space or memory..
can somebody explain this concept? thanks..
Hello, gonfreecks.
Ackerman function requires a lot of recursion.
Once a function goes too deeply in its recursion a java.lang.StackOverflowError occurs.
On my machine (Windows XP, 1 GB of memory) I tried a dummy recursive function and an StackOverflowError occured on recursion depths 6236 and 6260.
With Ackerman function once there is a calculation of expression like A(m,n) and m and n are positive numbers,it is going to recurse at least as deep as n-1.
For example if we have A(1,10000) it is going to recurse
A(1,10000)=A(0,A(1,9999))=A(0,A(0,A(0,A(1,9998)))= A(0,A(0,A(0,A(0,A(1,9997))))...... A(0,...A(1,0)) and it is already at recursion depth of
9999 which is greater than 6236 or 6260 on which the dummy function caused the exception on my computer.
While calculating A(4,3) the recursive calls which follow involve calls with much greater n than 10000, which we maybe can think of as some recursion depth limit.
For example, there must be a call to A(3,2^65536-3) while calculating A(4,3)
(
Ackermann function - Wikipedia, the free encyclopedia),
which would require recursion depth of at least 2^65536-4 , and that is way greater than 10000.
Even with A(4,1) there are calls A(m,n) with n greater than 4000 , and which cause exception on my computer.
So, A(4,3) recurses way too deep.
Hope it helped,
Valentin