Find GCD (Euclidean Algorithm) in Java
Problem
The greatest common divisor (GCD) of two numbers is the largest number that divides both of them evenly.
Given two integers, find their greatest common divisor.
Java Program
public class FindGCD {
public static void main(String[] args) {
int a = 48, b = 18;
int gcd = 1;
for (int i = Math.min(a, b); i >= 1; i--) {
if (a % i == 0 && b % i == 0) {
gcd = i;
break; // largest possible divisor found first, counting downward
}
}
System.out.println("GCD: " + gcd);
}
}Output
Core Logic
Trying every possible divisor from the smaller number down to 1, and stopping at the first one that divides both numbers evenly, finds the greatest common divisor directly.
- 1The loop starts at
Math.min(a, b), since no divisor of both numbers can be larger than the smaller one. - 2
icounts downward toward1, checking each candidate in turn. - 3
a % i == 0 && b % i == 0checks whetheridivides both numbers evenly. - 4The first
ithat satisfies both conditions is the greatest common divisor, and the loopbreaks immediately.
48 and 18, the loop counts down from 18 and finds that 6 is the first value dividing both evenly.Key Point: Starting from the smaller number and counting down guarantees the very first match found is the largest possible common divisor — there's no need to check further once one is found.
Why: In the worst case the loop checks every candidate from min(a, b) down to 1, and only a single variable is kept regardless of how large the numbers are.
Key Concepts
Approach 2: Euclidean Algorithm
public class FindGCDEuclidean {
static int gcd(int a, int b) {
if (b == 0) return a; // base case: b has shrunk to zero, a is the answer
return gcd(b, a % b); // replace the pair with (b, remainder)
}
public static void main(String[] args) {
int a = 48, b = 18;
System.out.println("GCD: " + gcd(a, b));
}
}
Output
Core Logic
Repeatedly replacing the larger number with the remainder of dividing it by the smaller one shrinks the pair down to the answer far faster than checking every candidate divisor.
- 1The base case
if (b == 0) return a;fires once the second number reaches zero — at that point,ais the GCD. - 2Every other call returns
gcd(b, a % b), replacing the pair with the smaller number and the remainder of dividing the two. - 3Each step's remainder is always smaller than the previous smaller number, so the pair shrinks quickly toward the base case.
- 4The recursion mirrors the ancient Euclidean algorithm exactly — no candidate divisors are ever tried.
48 and 18: gcd(48, 18) → gcd(18, 12) → gcd(12, 6) → gcd(6, 0), which returns 6.Key Point: This reaches the answer in just a handful of steps regardless of how large the numbers are, unlike the brute-force version whose cost grows with the smaller number itself.
Why: Each call shrinks the pair at a rate related to the Fibonacci sequence in reverse, so the number of calls — and the stack frames they use — grows logarithmically with the smaller number.