GCD and LCM
24 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Finding the greatest common divisor (GCD) by testing every divisor up to min(a, b) is far too slow when inputs reach 10⁹ or 10¹⁸. Euclid's 2,300-year-old remainder step shrinks the numbers exponentially, computing both GCD and least common multiple (LCM) in a handful of operations.
Euclid's Method for Greatest Common Divisor (GCD)
The GCD (greatest common divisor) of two numbers is the largest number that divides both. Euclid's algorithm finds it quickly with gcd(a, b) = gcd(b, a % b).
The greatest common divisor gcd(a, b) of two non-negative integers is the largest positive integer that divides both a and b without a remainder (with gcd(a, 0) = a for a > 0).
- Hand trace of
gcd(48, 18): - b = 18 ≠ 0. Remainder 48 mod 18 = 12. Advance to
(a = 18, b = 12). - b = 12 ≠ 0. Remainder 18 mod 12 = 6. Advance to
(a = 12, b = 6). - b = 6 ≠ 0. Remainder 12 mod 6 = 0. Advance to
(a = 6, b = 0). - b = 0, so return a = 6.
Example 1 · Brute force: try every divisor from min(a, b) down (O(min(a, b)) time, O(1) space)
public class GcdTryEveryDivisor { static long steps = 0;
public static int gcd(int a, int b) { for (int d = Math.min(a, b); d >= 1; d--) { steps++; if (a % d == 0 && b % d == 0) { return d; } } return Math.max(a, b); }
public static void main(String[] args) { System.out.println("gcd(48, 18) = " + gcd(48, 18) + " after " + steps + " tries"); steps = 0; System.out.println("gcd(1000003, 999983) = " + gcd(1_000_003, 999_983) + " after " + steps + " tries"); }}gcd(48, 18) = 6 after 13 tries gcd(1000003, 999983) = 1 after 999983 tries
What this code does
- The loop starts at the smaller number and counts down until one number divides both. For two numbers near a million it needs almost a million tries.
- It is correct but far too slow for inputs near 10⁹, which is why Euclid's method matters.
Example 2 · Better: Euclid by repeated subtraction (O(max(a, b)) time worst case, O(1) space)
public class GcdBySubtraction { static long steps = 0;
public static int gcd(int a, int b) { while (a != b) { steps++; if (a > b) { a -= b; } else { b -= a; } } return a; }
public static void main(String[] args) { System.out.println("gcd(48, 18) = " + gcd(48, 18) + " after " + steps + " subtractions"); steps = 0; System.out.println("gcd(1000003, 2) = " + gcd(1_000_003, 2) + " after " + steps + " subtractions"); }}gcd(48, 18) = 6 after 4 subtractions gcd(1000003, 2) = 1 after 500002 subtractions
What this code does
- Replacing the larger number by the difference keeps the GCD the same, and it needs no divisor search.
- It is faster for most inputs, yet gcd(1000003, 2) still takes 500002 subtractions. The remainder step in the next example does all of those subtractions at once.
Example 3 · Optimal: Euclid's remainder step, iterative and recursive (O(log min(a, b)) time, O(1) space)
public class EuclidGcdTraceDemo { public static int gcdIterative(int a, int b) { a = Math.abs(a); b = Math.abs(b); while (b != 0) { int remainder = a % b; a = b; b = remainder; } return a; }
public static int gcdRecursive(int a, int b) { return b == 0 ? Math.abs(a) : gcdRecursive(b, a % b); }
public static void main(String[] args) { System.out.println("gcd(48, 18) = " + gcdIterative(48, 18)); System.out.println("gcd(18, 48) = " + gcdRecursive(18, 48)); System.out.println("gcd(1071, 462) = " + gcdIterative(1071, 462)); System.out.println("gcd(0, 15) = " + gcdIterative(0, 15)); }}gcd(48, 18) = 6 gcd(18, 48) = 6 gcd(1071, 462) = 21 gcd(0, 15) = 15
What this code does
- Taking
Math.absat the start ensures a non-negative divisor even if a caller passes a negative coordinate delta. - When
a = 0andb = 15, the first loop step setsremainder = 0 % 15 = 0,a = 15,b = 0, and returns15. a % bremoves as many subtractions as possible in one step, so the numbers shrink by at least half every two steps.
A brute-force loop testing d = min(a, b) down to 1 takes O(min(a, b)) time, which is 10⁹ iterations when a and b are near 10⁹.
Euclid's algorithm uses the fact that any integer dividing both a and b also divides their remainder a mod b, and vice versa: gcd(a, b) = gcd(b, a mod b). Every two steps, the remainder shrinks by at least a factor of 2, so the loop finishes in O(log(min(a, b))) steps — at most about 45 iterations for any 32-bit int.
a < b initially, such as gcd(18, 48)? The very first step computes 18 mod 48 = 18 and swaps them to (48, 18) automatically — you do not need an if (a < b) check.LCM Without Overflow
The least common multiple lcm(a, b) is the smallest positive integer that is a multiple of both a and b.
Example 4 · Avoiding Intermediate Overflow in LCM
public class SafeLcmDemo { public static int gcd(int a, int b) { while (b != 0) { int r = a % b; a = b; b = r; } return a; }
public static int unsafeLcm(int a, int b) { return (a * b) / gcd(a, b); }
public static int safeIntLcm(int a, int b) { if (a == 0 || b == 0) return 0; return (a / gcd(a, b)) * b; }
public static long safeLongLcm(long a, long b) { if (a == 0 || b == 0) return 0; long x = a; long y = b; while (y != 0) { long r = x % y; x = y; y = r; } return (a / x) * b; }
public static void main(String[] args) { int a = 50_000; int b = 60_000; System.out.println("unsafeLcm(50000, 60000) = " + unsafeLcm(a, b)); System.out.println("safeIntLcm(50000, 60000) = " + safeIntLcm(a, b)); System.out.println("safeLongLcm(100000, 99999) = " + safeLongLcm(100_000L, 99_999L)); }}unsafeLcm(50000, 60000) = -129496 safeIntLcm(50000, 60000) = 300000 safeLongLcm(100000, 99999) = 9999900000
What this code does
- For
50_000and60_000, the true LCM is300_000(well withinint), yet50_000 * 60_000 = 3_000_000_000overflows 32-bitintto-1_294_967_296before dividing by10_000. - Dividing first (
50_000 / 10_000 = 5, then5 * 60_000 = 300_000) eliminates the unnecessary intermediate spike.
Because every prime factor is shared between gcd(a, b) and lcm(a, b), any two positive integers satisfy the identity a × b = gcd(a, b) × lcm(a, b).
Writing (a * b) / gcd(a, b) in Java is a classic overflow trap: even when the final LCM fits comfortably inside a 32-bit int, the intermediate product a * b can overflow before the division happens. Because gcd(a, b) always divides a evenly, you should divide first, then multiply, and widen to long when the LCM itself could exceed Integer.MAX_VALUE: (a / gcd(a, b)) * (long) b.
- Unsafe formula:
(a * b) / gcd(a, b)— multiplies first and can overflow even for medium inputs like50_000and60_000. - Safe
intformula (when LCM fits inint):(a / gcd(a, b)) * b— exact divisiona / gcd(a, b)never leaves a remainder. - Safe
longformula (general case):(a / gcd(a, b)) * (long) b— widens to 64-bit before the multiplication.
Real World: When Repeating Schedules Line Up
Whenever two or more periodic events repeat every t₁, t₂, …, tₖ units of time and start together at t = 0, the next time they all fire simultaneously is lcm(t₁, t₂, …, tₖ).
Example 5 · Real World: Aligning Cron Schedules and Simplifying Fractions
public class ScheduleAlignmentDemo { public static long gcd(long a, long b) { while (b != 0) { long r = a % b; a = b; b = r; } return a; }
public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; }
public static void main(String[] args) { int[] intervalsMinutes = {12, 18, 30}; long alignMinutes = intervalsMinutes[0]; for (int i = 1; i < intervalsMinutes.length; i++) { alignMinutes = lcm(alignMinutes, intervalsMinutes[i]); } System.out.println("All 3 jobs align every: " + alignMinutes + " minutes");
long num = 48; long den = 180; long g = gcd(num, den); System.out.println("48/180 reduced: " + (num / g) + "/" + (den / g)); }}All 3 jobs align every: 180 minutes 48/180 reduced: 4/15
What this code does
lcm(12, 18) = 36, andlcm(36, 30) = 180, so all three services fire together every 180 minutes (3 hours).- Dividing both numerator
48and denominator180bygcd(48, 180) = 12produces the irreducible fraction4/15.
Because both GCD and LCM are associative, you can fold them across an array of n numbers one pair at a time: lcm(a, b, c) = lcm(lcm(a, b), c).
GCD also powers exact rational arithmetic: to store a fraction p / q in canonical lowest terms (for example, as a slope key in a hash map so 2/4 and 3/6 collide to 1/2), divide both numerator and denominator by g = gcd(|p|, |q|).
- Multi-number GCD:
result = arr[0]; for (int x : arr) result = gcd(result, x);. - Multi-number LCM:
result = arr[0]; for (int x : arr) result = lcm(result, x);. - Reducing a fraction p / q: divide both p and q by gcd(|p|, |q|).
Next step
Check your understanding
10 quick questions