Answer:
import java.util.Scanner;
public class Gcd
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter two numbers to find their GCD: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
if(number1 > 0 && number2 > 0)
System.out.println("GCD of " + number1 +" and " + number2 +" is: " + findGCD(number1, number2));
else
System.out.println("Invalid Input!");
}
public static int findGCD(int number1, int number2) {
if(number2 == 0){
return number1;
}
return findGCD(number2, number1 % number2);
}
}
Explanation:
To be able to find GCD, we need to factorize the numbers and multiply common factors.
- <u>Inside the function:</u>
- Recursively divide <em>number1</em> by <em>number2</em> until <em>number2</em> is equal to zero.
- Return <em>number1</em> when the <em>number2</em> is equal to zero. That means we found all the divisors of <em>number1</em>
- <u>Inside the main:</u>
- Ask user to input numbers
- Check if both numbers are greater than zero
- If they satisfy the condition, call the method and print the result.