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