|
| 1 | +/* |
| 2 | + * Ackermann Function is given by : |
| 3 | + * A (m , n) = n + 1, if m = 0 |
| 4 | + = A (m - 1, 1) if m > 0 and n = 0 |
| 5 | + = A (m - 1, A(m, n - 1)) if m > 0 and n > 0 |
| 6 | + */ |
| 7 | + |
| 8 | +import java.math.BigInteger; |
| 9 | +import java.util.Stack; |
| 10 | + |
| 11 | +// This method overcomes the problem of Stack Overflow Exception |
| 12 | +public class AckermannNonRecursive { |
| 13 | + |
| 14 | + private static BigInteger ackermann(BigInteger m, BigInteger n) { |
| 15 | + |
| 16 | + Stack<BigInteger> ack = new Stack<BigInteger>(); // Creating a stack to store the values |
| 17 | + ack.push(m); |
| 18 | + |
| 19 | + while (!ack.isEmpty()) { // Looping while the stack is not empty |
| 20 | + m = ack.pop(); // Assigning m the value of top element of the stack |
| 21 | + if (m.equals(BigInteger.ZERO)) // If m = 0, n = n + 1 |
| 22 | + n = n.add(BigInteger.ONE); |
| 23 | + else if (n.equals(BigInteger.ZERO)) { // If n = 0, push m - 1 in the stack and update the value of n to 1 |
| 24 | + BigInteger temp = m.subtract(BigInteger.ONE); |
| 25 | + ack.push(temp); |
| 26 | + n = BigInteger.ONE; |
| 27 | + } |
| 28 | + else { // If n > 0 and m > 0, push m - 1 and m in the stack respectively and subtract 1 from n |
| 29 | + BigInteger temp = m.subtract(BigInteger.ONE); |
| 30 | + ack.push(temp); |
| 31 | + ack.push(m); |
| 32 | + n = n.subtract(BigInteger.ONE); |
| 33 | + } |
| 34 | + } |
| 35 | + return n; |
| 36 | + } |
| 37 | + |
| 38 | + public static void main(String[] args) { |
| 39 | + System.out.println(ackermann(new BigInteger("3"), new BigInteger("4"))); |
| 40 | + } |
| 41 | +} |
0 commit comments