Compute the greatest common divisor of two integers (e.g. gcd(48, 18) = 6).
Use the Euclidean algorithm: gcd(a, b) = gcd(b, a % b), repeating until b is zero, at which point a is the GCD. This is far faster than trial division — O(log(min(a, b))). The LCM follows as a * b / gcd(a, b).
public static int gcd(int a, int b) {
while (b != 0) { int t = b; b = a % b; a = t; }
return a;
}function gcd(a, b) {
while (b !== 0) { [a, b] = [b, a % b]; }
return a;
}def gcd(a, b):
while b:
a, b = b, a % b
return aGCD reduces fractions, computes aspect ratios, and schedules repeating intervals — a small but genuinely reused primitive.
A candidate finds the GCD by looping from min(a,b) down to 1. Why is Euclid better?