Skip to content

Commit 9df8a7a

Browse files
Added Description
1 parent ae53a5e commit 9df8a7a

3 files changed

Lines changed: 51 additions & 34 deletions

File tree

‎src/algo/recursion/Ackermann.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
/*
2+
* the Ackermann function is one of the simplest and earliest-discovered examples of a total computable function that is not primitive recursive.
3+
* All primitive recursive functions are total and computable, but the Ackermann function illustrates that not all total computable functions are primitive recursive.
4+
* Ackermann Function is given by :
5+
* A (m , n) = n + 1, if m = 0
6+
= A (m - 1, 1) if m > 0 and n = 0
7+
= A (m - 1, A(m, n - 1)) if m > 0 and n > 0
8+
* As this function may return large values, BigInteger class is used.
9+
*/
10+
111
import java.math.BigInteger;
212

313
// This method may give Stack Overflow Exception

‎src/algo/recursion/AckermannModified.java‎

Lines changed: 0 additions & 34 deletions
This file was deleted.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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

Comments
 (0)