In: Computer Science
JAVA CLASS
Greatest Common Divisor Finder
Enter first number: 12
Enter second number: 8
Greatest common divisor: 4
Continue? (y/n): y
Enter first number: 77
Enter second number: 33
Greatest common divisor: 11
Continue? (y/n): y
Enter first number: 441
Enter second number: 252
Greatest common divisor: 63
Continue? (y/n): n
The formula for finding the greatest common divisor of two positive integers x and y follows the Euclidean algorithm as follows:
1. Subtract x from y repeatedly until y <
x.
2. Swap the values of x and y.
3. Repeat steps 1 and 2 until x = 0.
4. y is the greatest common divisor of the two
numbers.
You can use one loop for step 1 of the algorithm nested within a second loop for step 3.
Assume that the user will enter valid integers for both numbers.
The application should continue only if the user enters 'y' or 'Y' to continue.
//GCDFinder.java
import java.util.Scanner;
public class GCDFinder {
public static void main(String[] args) {
int a, b, t;
Scanner scanner = new Scanner(System.in);
char ch = 'y';
System.out.println("Greatest Common Divisor Finder");
while (ch=='y') {
System.out.print("Enter first number: ");
a = scanner.nextInt();
System.out.print("Enter second number: ");
b = scanner.nextInt();
if (b > a) {
t = a;
a = b;
b = t;
}
while (b != 0) {
t = b;
b = a % t;
a = t;
}
System.out.println("Greatest common divisor: " + a);
System.out.print("Continue? (y/n): ");
ch = scanner.next().charAt(0);
}
}
}


