In: Computer Science
Ackermann’s function is a recursive mathematical algorithm that can be used to test how well a computer performs recursion. Write a method ackermann(m, n), which solves Ackermann’s function. Use the following logic in your method:
If m = 0, then return n + 1
If n = 0, then return ackermann(m-1, 1)
Otherwise, return ackermann(m -1, ackermann(m, n - 1))
Test your method in a java program that displays the return values of the following method calls:
ackermann(0, 0), ackermann(0, 1), ackermann(1, 1), ackermann(1, 2) ackermann(1, 3), ackermann(2, 2), ackermann(3, 2)
Explanation:
Here is the code which has the method ackermann taking the integer values m and n.
Then the if conditions are applied using recursion as given in the pseudocode above.
Then the given calls are made.
Code:
public class Main
{
public static int ackermann(int m, int n)
{
if(m==0)
return n+1;
if(n==0)
return ackermann(m-1, 1);
return ackermann(m-1, ackermann(m, n-1));
}
public static void main(String[] args) {
System.out.println(ackermann(0,
0));
System.out.println(ackermann(0,
1));
System.out.println(ackermann(1,
1));
System.out.println(ackermann(1,
2));
System.out.println(ackermann(1,
3));
System.out.println(ackermann(2,
2));
System.out.println(ackermann(3,
2));
}
}
output:
PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!
PLEASE COMMENT IF YOU NEED ANY HELP!