Look at both numbers
Determine the lowest number
While loop till lowest number
Compare a % x and b % x for true:  To get GCD.

 

 

public class GCD {
public static void main(String[] args) {
System.out.println();
getGreatestCommonDivisor(25, 15);
getGreatestCommonDivisor(25, 25);
getGreatestCommonDivisor(12, 30);
getGreatestCommonDivisor(40, 140);
getGreatestCommonDivisor(81, 153);
getGreatestCommonDivisor(559, 1000);
getGreatestCommonDivisor(9999, 29997);

}


public static void getGreatestCommonDivisor(int a, int b) {
int while_max = 0;
int x = 1;
int GrtComDemon = 0;

// determines the lowest of the two numbers for the while loop to save cycles.
if (a < b) {
while_max = b + 1;
} else {
while_max = a + 1;
}

// if two numbers are the same, they are the GCD
if (a == b) {
System.out.println("Greatest Common Denominator of " + a + " and " + b + " is " + a);
} else {

while (x < while_max) {
if ((a % x == 0) && (b % x == 0)) GrtComDemon = x;
x++;
}
System.out.println("Greatest Common Demoninator of " + a + " and " + b + " is " + GrtComDemon);
}


}
}
C:\Users\netadmin\.jdks\openjdk-23.0.1\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2024.2.4\lib\idea_rt.jar=64431:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2024.2.4\bin" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath C:\Users\netadmin\IdeaProjects\GCD\out\production\GCD GCD

Greatest Common Demoninator of 25 and 15 is 5
Greatest Common Demoninator of 25 and 25 is 25
Greatest Common Demoninator of 12 and 30 is 6
Greatest Common Demoninator of 40 and 140 is 20
Greatest Common Demoninator of 81 and 153 is 9
Greatest Common Demoninator of 559 and 1000 is 1
Greatest Common Demoninator of 9999 and 29997 is 9999

Process finished with exit code 0