Compute the Greatest Common Divisor (GCD) using Recursion. Write a recursive met
ID: 3823316 • Letter: C
Question
Compute the Greatest Common Divisor (GCD) using Recursion. Write a recursive method to find the GCD. Write a test program to prompt the user to enter two integers and displays their GCD.
The findGCD(m, n) method can also be defined recursively as follows:
- If m % n is 0, findGCD(m, n) is n;
- Otherwise, findGCD(m, n) is findGCD(n, m % n).
Note:
Neither value can be less than 1; verify user input
CODE:
import java.util.Scanner;
public class GCDCalculator {
public static int findGCD (int m, int n) {
// FIXME: Complete the recursive method; If m % n is 0, findGCD(m, n) is n; Otherwise, findGCD(m, n) is findGCD(n, m % n).
}
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
int num1 = 0; // First input to findGCD
int num2 = 0; // Second input to findGCD
int gcd = 0; // Result of GCD
// FIXME: Complete the statements to prompt the user for inputs
System.out.println("Enter the first number: ");
System.out.println("Enter the second number: ");
// FIXME: Check user values are not less than 1; call recursive findGCD function
if (/* Your solution goes in here. */) {
System.out.println("Note: Neither value can be less than 1.");
}
else {
gcd = findGCD(num1, num2);
System.out.println("The GCD is: " + gcd);
}
return;
}
}
Explanation / Answer
import java.util.Scanner;
public class GCDCalculator
{
public static int findGCD (int m, int n)
{
// FIXME: Complete the recursive method; If m % n is 0, findGCD(m, n) is n; Otherwise, findGCD(m, n) is findGCD(n, m % n).
if(n==0)
return m;
else
return findGCD(n,m%n);
}
public static void main (String[] args)
{
Scanner scnr = new Scanner(System.in);
int num1 = 0; // First input to findGCD
int num2 = 0; // Second input to findGCD
int gcd = 0; // Result of GCD
// FIXME: Complete the statements to prompt the user for inputs
System.out.println("Enter the first number: ");
num1=scnr.nextInt();
System.out.println("Enter the second number: ");
num2=scnr.nextInt();
// FIXME: Check user values are not less than 1; call recursive findGCD function
if (num1<0 || num2<0 )
{
System.out.println("Note: Neither value can be less than 1.");
}
else
{
gcd =findGCD(num1, num2);
System.out.println("The GCD is: " + gcd);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.