Home
DSA Visualizer
Mathematics
GCD & LCM
GCD & LCM
The GCD (greatest common divisor) and LCM (least common multiple) of two numbers are computed with the Euclidean algorithm.
SHRINK
mod
The chain so far
gcd(48, 18). Any number dividing both also divides their remainder — which is what lets the pair shrink without changing the answer.
Next
48 mod 18 = 12. Replace the pair with (18, 12) — same divisors, smaller numbers.
A
B
Intuition
If a number divides both A and B, it must also divide their difference (A - B). By extension, it divides the remainder of A % B. We can keep reducing the problem until the remainder is 0.
Concept
- GCD (Greatest Common Divisor): The largest number that divides both A and B without leaving a remainder.
- LCM (Least Common Multiple): The smallest number that is a multiple of both A and B.
- Relation:
LCM(A, B) = (A * B) / GCD(A, B)
How it Works
Euclidean Algorithm:
- Calculate remainder
R = A % B. - If
R == 0, thenBis the GCD. - Otherwise, set
A = BandB = R, and repeat.
Step-by-Step Breakdown
Watch the visualization:
- See how the numbers shrink rapidly.
- The process stops when the remainder becomes 0.
- The last non-zero divisor is the GCD.
Trace: gcd(48, 18), then lcm(48, 18)
gcd(48, 18)
48 % 18 = 12. The remainder is not zero, so the pair becomes (18, 12) — any divisor of 48 and 18 also divides 12.
r = 12
gcd(18, 12)
18 % 12 = 6. Still not zero, so the pair becomes (12, 6).
r = 6
gcd(12, 6)
12 % 6 = 0. The remainder has vanished, so the divisor standing here is the answer.
r = 0
result
Three divisions. The last non-zero divisor is the GCD, and 6 does divide both 48 and 18.
gcd = 6
lcm(48, 18)
48 / 6 * 18. Dividing before multiplying keeps the intermediate value at 8 rather than the 864 that 48 * 18 would have produced first.
lcm = 144
When to Use
- Simplifying fractions.
- Scheduling problems (LCM).
- Cryptography (RSA algorithm).
When NOT to Use
- When numbers are extremely large (though it's still very efficient, O(log(min(A, B)))).
How to Identify
"Common divisor", "Simultaneous events (LCM)", "Simplify ratio".
Applying for software engineering roles? Free, no sign-up:
