The GCD is the largest number that divides two numbers; the LCM is the smallest number both divide.
Video lesson · Chapter 1 of 5
Cut the widest tile
A remainder carries the same divisors
Trace simultaneous assignment
Synchronize the machines
Choose what the answer must do
0:00 / 4:20
GCD and LCM
1:24·Reel
Read caption
Tika schedules two drums with periods twelve and eighteen using Euclid’s algorithm and the least common multiple.
Biggest shared unit. Smallest shared return.
How it works
Step through the idea, or press Play.
Step 1 of 3
Replace and repeat. Swap the pair (a, b) for (b, a mod b) until b is 0; whatever is left in a is the GCD
Get the LCM for free. Divide one number by the GCD and multiply by the other: lcm(48, 18) = 48 / 6 × 18 = 144
Spot it in problems. Reducing fractions, tiling, cycles lining up and reachable amounts are all GCD or LCM questions in disguise
Understand it
Start here
What GCD and LCM are
The greatest common divisorgcd(a,b) is the largest positive integer that divides both a and b with no remainder. The least common multiplelcm(a,b) is the smallest positive integer that both a and b divide. For 12 and 18: the GCD is 6 and the LCM is 36.
The definitions
gcd(a,b)=max{d:d∣a and d∣b}lcm(a,b)=min{m>0:a∣m and b∣m}
d∣a reads "d divides a": amodd=0. The GCD is the biggest shared divisor; the LCM is the smallest shared multiple.
GCD: the shared piece
The longest equal length you can cut two ropes into. Ropes of 48 cm and 18 cm cut evenly into 6 cm pieces.
LCM: the meeting point
The first time two repeating events happen together. Buses every 12 and 18 minutes meet at minute 36.
Coprime: nothing shared
When gcd(a,b)=1 the numbers are coprime, like 8 and 15. Then lcm(a,b)=a×b.
By hand
Listing and prime factors
12
18
Shared
Divisors
1, 2, 3, 4, 6, 12
1, 2, 3, 6, 9, 18
1, 2, 3, 6: the largest is 6
Multiples
12, 24, 36, 48, 60, 72
18, 36, 54, 72
36, 72, ...: the smallest is 36
Listing works for small numbers, but it is O(n) work and hopeless for numbers with ten digits.
The GCD takes the smaller power of every prime; the LCM takes the larger one. Factoring big numbers is slow, though, which is why code uses Euclid instead.
The key idea
Euclid's rule: replace and repeat
The Euclidean algorithm
gcd(a,b)=gcd(b,amodb)gcd(a,0)=a
Keep applying the rule until the second number is 0. The first number is then the GCD. Written down around 300 BC, it is one of the oldest algorithms still in daily use.
Why does it work? Write a=qb+r where r=amodb. Any number d that divides both a and b also divides a−qb=r. And any d that divides b and r also divides qb+r=a. So the pairs (a,b) and (b,r) have exactly the same common divisors, and therefore the same greatest one.
The Euclid loop
flowchart TD
S["Start with a and b"] --> Q{"Is b equal to 0?"}
Q -- no --> R["r = a mod b"]
R --> P["a = b, then b = r"]
P --> Q
Q -- yes --> D["Return a: the GCD"]
One comparison and one remainder per pass. The pair only ever gets smaller.
Worked example
gcd(48, 18) step by step
Step
Division
New pair
1
48=18×2+12
(18,12)
2
18=12×1+6
(12,6)
3
12=6×2+0
(6,0): stop, the GCD is 6
Three divisions. The last non-zero remainder, 6, is the GCD.
The pair shrinking
flowchart LR
A["(48, 18)"] -- "48 mod 18 = 12" --> B["(18, 12)"]
B -- "18 mod 12 = 6" --> C["(12, 6)"]
C -- "12 mod 6 = 0" --> D["(6, 0): gcd = 6"]
Each arrow is one loop pass: a, b = b, a % b.
Then the LCM
lcm(48,18)=gcd(48,18)48×18=648×18=144
Check: 6×144=864=48×18.
Geometry
GCD as the largest square tile
Picture a floor w wide and h tall. A square tile of side s covers it exactly only if s divides both w and h. The largest such tile has side gcd(w,h), and you need gw×gh of them. A 6×4 floor takes six 2×2 tiles; a 48×18 floor takes 8×3=24 tiles of 6×6.
Euclid with scissors
flowchart TD
R0["Rectangle 6 x 4"] --> C1["Cut the biggest square: 4 x 4"]
C1 --> R1["Leftover strip: 4 x 2, because 6 mod 4 = 2"]
R1 --> C2["Cut the biggest squares: two 2 x 2"]
C2 --> R2["Nothing left, because 4 mod 2 = 0"]
R2 --> G["The last square size, 2, is gcd(6, 4)"]
Cutting the largest square off a rectangle, again and again, is exactly the Euclidean algorithm.
LCM
When cycles line up
LCM from GCD
lcm(a,b)=gcd(a,b)∣a⋅b∣=gcd(a,b)∣a∣⋅∣b∣
The second form divides first, so the intermediate value is never bigger than the answer.Bus A every 12 minutes, bus B every 18
1A leaves12, 24, 36, 48, ...
2B leaves18, 36, 54, ...
3gcd(12, 18) = 6Euclid: 18 → 12 → 6 → 0
4Meet at 3612 / 6 × 18 = 36, then every 36 minutes
36 ÷ 12 = 3 trips for A and 36 ÷ 18 = 2 trips for B, both whole numbers.
Speed
Why Euclid is O(log min(a, b))
The halving lemma
a≥b>0⇒amodb<2a
If b≤2a, the remainder is below b≤2a. If b>2a, then amodb=a−b<2a. Either way the remainder is under half of a.
After two steps the pair (a,b) becomes (amodb,…), so the larger number at least halves every two steps. Halving can only happen about log2 times, which gives at most about 2log2min(a,b) divisions. (After the first step the larger number is min(a,b), which is why the bound uses the smaller input.)
The worst case is Fibonacci
gcd(Fn+1,Fn):34→21→13→8→5→3→2→1→0steps≤5×(digits of min(a,b))
Consecutive Fibonacci numbers make every quotient 1, the slowest possible shrink. Lamé's theorem caps the steps at five per decimal digit; any pair with the smaller number below a billion needs at most 43 divisions.
Method
Time
gcd of two numbers near 109
Try every divisor from min(a,b) down
O(min(a,b))
up to a billion checks
Prime factorisation
slow for large numbers
trial division up to n≈31,623
Euclid, iterative
O(logmin(a,b)) time, O(1) space
at most 43 divisions
Euclid, recursive
O(logmin(a,b)) time and stack
same count, plus call frames
In code
GCD and LCM in Python
Python
importmathfrom functools import reducedefgcd(a, b):while b != 0: a, b = b, a % breturnabs(a)defgcd_recursive(a, b):returnabs(a) if b == 0elsegcd_recursive(b, a % b)deflcm(a, b):if a == 0or b == 0:return0returnabs(a // gcd(a, b) * b)print(gcd(48, 18), gcd_recursive(48, 18), math.gcd(48, 18)) # 6 6 6print(lcm(48, 18), math.lcm(48, 18)) # 144 144print(reduce(gcd, [12, 18, 24])) # 6print(reduce(lcm, [4, 6, 8])) # 24
Iterative, recursive and library versions agree.Edit and run it in your browser
Language
GCD
LCM
Python 3.9+
math.gcd(*nums)
math.lcm(*nums)
C++17
std::gcd(a, b)
std::lcm(a, b)
Java
BigInteger.gcd, or write the loop
a / gcd(a, b) * b with long
JavaScript
write the loop
a / gcd(a, b) * b, or BigInt for large values
For a list, fold the two-number version across it: gcd(a,b,c)=gcd(gcd(a,b),c), and the same for LCM.
Edge cases
Zero, negatives and coprimes
Input
Result
Why
gcd(0,15)
15
Every number divides 0, so the largest divisor of 15 wins
gcd(0,0)
0
A convention; math.gcd(0, 0) returns 0
lcm(0,b)
0
Return 0 directly; the formula would divide by gcd(0,0)=0 when both are 0
gcd(−12,18)
6
The GCD is defined as positive; take abs or use math.gcd
gcd(8,15)
1
Coprime: no shared prime factor, so lcm=120=8×15
gcd(n,n), gcd(1,n)
n, 1
A number shares everything with itself and nothing with 1
Safe habits
a, b = b, a % b in one tuple assignment.
Loop while b != 0 and return a.
a // gcd(a, b) * b for the LCM.
Return 0 for an LCM when either input is 0.
Common bugs
a = b then b = a % b: the remainder is always 0.
while a % b: crashes when b is 0.
a * b // gcd(a, b): overflows in fixed-width languages.
Taking the product of a list as its LCM.
Going further
Bézout and the extended algorithm
Bézout's identity
∃x,y∈Z:ax+by=gcd(a,b)e.g.48⋅(−1)+18⋅3=6
The amounts you can make from steps of size a and b (forwards and backwards) are exactly the multiples of gcd(a,b). This is the whole idea behind the water jug puzzle.
Python
defext_gcd(a, b):if b == 0:return a, 1, 0 g, x, y = ext_gcd(b, a % b)return g, y, x - (a // b) * yg, x, y = ext_gcd(48, 18)print(g, x, y, 48 * x + 18 * y) # 6 -1 3 6
Extended Euclid returns the GCD and the Bézout coefficients. It is how modular inverses are computed in RSA.Edit and run it in your browser
Pattern spotting
GCD or LCM?
Which one does the problem want?
flowchart TD
Q1{"Largest equal piece, group or tile that divides everything?"} -- yes --> G["GCD"]
Q1 -- no --> Q2{"First time repeating cycles line up?"}
Q2 -- yes --> L["LCM = a / gcd * b"]
Q2 -- no --> Q3{"Which totals can ax + by make?"}
Q3 -- yes --> B["Multiples of the GCD: Bezout"]
Q3 -- no --> Q4{"Simplify a ratio or fraction?"}
Q4 -- yes --> F["Divide both by the GCD"]
Q4 -- no --> O["Probably not a GCD problem"]
Most number-theory warm-ups in interviews land in one of these four boxes.
Where it shows up
Fractions
1812 reduces to 32 by dividing both by gcd=6. Adding fractions needs the LCM of the denominators.
Cryptography
RSA picks an exponent coprime to φ(n) and finds its inverse with extended Euclid.
Scheduling
Jobs with periods 4, 6 and 10 all run together every lcm=60 ticks.
Hashing
Double hashing and linear probing visit every slot only when the step and table size are coprime.
GCD of strings
Two strings share a repeating block exactly when s + t == t + s; its length is gcd(∣s∣,∣t∣).
Array rotation
Rotating n items by k in place splits them into gcd(n,k) independent cycles.
Recap
Key takeaways
Key points
gcd(a,b) is the largest shared divisor; lcm(a,b) is the smallest shared multiple.
Euclid: gcd(a,b)=gcd(b,amodb) until b=0. In code: a, b = b, a % b.
It works because (a,b) and (b,amodb) have exactly the same common divisors.
amodb<a/2, so the work is O(logmin(a,b)); Fibonacci pairs are the worst case.
lcm(a,b)=a/gcd(a,b)×b, and gcd×lcm=a×b.
Coprime means gcd=1. gcd(n,0)=n, and an LCM with a 0 input is 0.
GCD answers largest equal piece; LCM answers when cycles meet; Bézout answers which amounts are reachable.