GCD with Euclid's algorithm (and LCM for free)
(a, b) = gcd(b, a % b) until b is 0. It's O(log) fast, and (a, b) = a × b / gcd(a, b).
The idea
Any number dividing both a and b also divides a % b (the remainder is a minus some multiple of b). So gcd(a, b) = gcd(b, a % b). The numbers shrink fast, and when the second one hits 0, the first is the answer.
Once you have the gcd, the least common multiple follows: lcm(a, b) = a / gcd(a, b) × b (divide first to keep numbers small).
Worked example
gcd(48, 18)
- gcd(48, 18) → 48 % 18 = 12 → gcd(18, 12)
- 18 % 12 = 6 → gcd(12, 6)
- 12 % 6 = 0 → gcd(6, 0) = 6. And lcm = 48 / 6 × 18 = 144.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
gcd(48, 18)
Solution · Pythonline 1
def gcd(a, b):while b:a, b = b, a % breturn a def lcm(a, b):return a // gcd(a, b) * b # Python also has math.gcd and math.lcm.Step 1 of 5· line 1
gcd(a, b) = gcd(b, a % b): whatever divides both a and b also divides the remainder. The numbers shrink fast.
O(log(min(a, b))) steps.
How to spot it
- “largest string / number that divides both”, fractions, “every k-th and every m-th”, repeating that line up.
Common mistakes
- Computing a × b before dividing in Java/C++ ().
- Looping down from min(a, b) to 1: correct but instead of .
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →