In: Computer Science
The Ackermann function is a function created by Wilhelm Ackermann in the late 1920s. For non-negative integers m and n, the Ackermann function is defined as
EMBED Equation.3
Write a method to recursively computer the Ackermann function. Note that the Ackermann function grows extremely quickly for even small values of m and n. Test your method with the following values but be aware that if m is greater than 3 and n is greater than 1, it will take a very long time to compute.
import java.util.Scanner;
public class HelloWorld
{
public static void main (String [] args)
{
userMenu();
}
public static void userMenu()
{
Scanner scan = new Scanner(System.in);
System.out.println("");
System.out.println("If you wish to use the ackermann function enter
\"1\" \nIf you wish to exit enter \"2\"");
int userInput = scan.nextInt();
switch(userInput)
{
case 1: System.out.print("Enter an \"m\" value: ");
int x = scan.nextInt();
System.out.print("Enter a \"n\" value: ");
int y = scan.nextInt();
int m = 0;
int n = 0;
System.out.println("\nThe Ackermann
Function at \"m\" = " + m + " and \"n\" = " + n + " is: " +
Ackermann(m,n));
userMenu();
case 2: System.out.println("");
System.out.println("Program Terminated");
System.exit(0);
default: System.out.println("");
System.out.println("Please enter a valid option");
userMenu();
}
}
public static int Ackermann(int m, int n)
{
if(n >= 0 && m >= 0)
{
if(m == 0)
{
return (n + 1);
}
if(m > 0 && n == 0)
{
return (Ackermann(m-1,1));
}
if(m > 0 && n > 0)
{
return (Ackermann((m-1),Ackermann(m,(n-1))));
}
else
{
return 0;
}
}
else
{
System.out.println("The values entered for \"x\" and \"y\" are not
valid");
return 0;
}
}
}