In: Computer Science
Objectives: use Scite
1. Use recursion to solve a problem
2. Create classes to model objects
Problem 1: Compute greatest common divisor using recursion (filename: TestRecusiveGCD.java) The gcd(m, n) can be defined recursively as follows: If m % n is 0, gcd (m, n) is n. Otherwise, gcd(m, n) is gcd(n, m % n). Write a recursive method to find the GCD of two given integers. Write a test program that prompts the user to enter two integers, calls the method above, and displays their GCD.
Problem 2: Print the digits in an integer reversely (filename: TestReverseDigits.java) Write a recursive method that displays an integer value reversely on the console using the following header: public static void reverseDisplay(int value) For example, reverseDisplay(12345) displays 54321. Write a test program that prompts the user to enter an integer, invokes the method above, and displays its reversal.
TestRecusiveGCD.java
class TestRecusiveGCD
{
public static void main(String[] args)
{
System.out.println(gcd(2,5));
System.out.println(gcd(10,5));
System.out.println(gcd(24,16));
System.out.println(gcd(11,12));
}
public static int gcd(int m, int n)
{
if(m%n==0)
{
return n;
}
return gcd(m,m%n);
}
}
output screenshot:
TestReverseDigits.java
class TestReverseDigits
{
public static void main(String[] args)
{
reverseDisplay(12345);
System.out.println();
reverseDisplay(10000);
System.out.println();
reverseDisplay(1234567890);
System.out.println();
}
public static void reverseDisplay(int n)
{
if(n<10)
{
System.out.print(n);
return;
}
System.out.print(n%10);
reverseDisplay(n/10);
}
}
output screenshot: