Created
November 21, 2014 20:44
-
-
Save nboubakr/e63c25af093e175cacb2 to your computer and use it in GitHub Desktop.
Ackermann Function: recursive and non recursive version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
/** | |
* | |
* @author Boubakr | |
*/ | |
public class Ackermann { | |
public static int RecursiveAckerman(int m, int n) { | |
if (m == 0) { | |
return (n + 1); | |
} else if (m > 0 && n == 0) { | |
return RecursiveAckerman(m - 1, 1); | |
} else { | |
return RecursiveAckerman(m - 1, RecursiveAckerman(m, n - 1)); | |
} | |
} | |
public static int NonRecursiveAckerman(int m, int n) { | |
Stack<Integer> stack = new Stack<Integer>(); | |
stack.add(m); | |
while (!stack.isEmpty()) { | |
m = stack.pop(); | |
if (m == 0 || n == 0) { | |
n += m + 1; | |
} else { | |
stack.add(--m); | |
stack.add(++m); | |
n--; | |
} | |
} | |
return n; | |
} | |
public static void main(String[] args) { | |
System.out.println("RecursiveAckerman(1, 2) : " + RecursiveAckerman(1, 2)); | |
System.out.println("NonRecursiveAckerman(1, 2): " + NonRecursiveAckerman(1, 2)); | |
} | |
} |
Yeah! This code doesn't work correctly. Could you please make editing to the code to check it.
I changed this part } else if (m > 0 && n == 0) {
to } else if (n == 0) {
and it worked
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code doesn't work correctly. If you try e.g. Ackermann(3,3) it must return 61, but yours return 53.