AlgoViz

GCD & LCM

easy 14 min

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

0:00 / 4:20

GCD and LCM

1:24Reel

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

Understand it

Start here

What GCD and LCM are

The greatest common divisor gcd⁡(a,b)\gcd(a, b) is the largest positive integer that divides both aa and bb with no remainder. The least common multiple lcm⁡(a,b)\operatorname{lcm}(a, b) is the smallest positive integer that both aa and bb 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 }\gcd(a, b) = \max\{\, d : d \mid a \text{ and } d \mid b \,\} \qquad \operatorname{lcm}(a, b) = \min\{\, m > 0 : a \mid m \text{ and } b \mid m \,\}
d∣ad \mid a reads "dd divides aa": a mod d=0a \bmod d = 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\gcd(a, b) = 1 the numbers are coprime, like 8 and 15. Then lcm⁡(a,b)=a×b\operatorname{lcm}(a, b) = a \times b.

By hand

Listing and prime factors

1218Shared
Divisors1, 2, 3, 4, 6, 121, 2, 3, 6, 9, 181, 2, 3, 6: the largest is 6
Multiples12, 24, 36, 48, 60, 7218, 36, 54, 7236, 72, ...: the smallest is 36
Listing works for small numbers, but it is O(n)O(n) work and hopeless for numbers with ten digits.

Through prime factors

12=22⋅31,18=21⋅32⇒gcd⁡=2min⁡(2,1)⋅3min⁡(1,2)=6,lcm⁡=2max⁡(2,1)⋅3max⁡(1,2)=3612 = 2^2 \cdot 3^1, \quad 18 = 2^1 \cdot 3^2 \quad\Rightarrow\quad \gcd = 2^{\min(2,1)} \cdot 3^{\min(1,2)} = 6, \quad \operatorname{lcm} = 2^{\max(2,1)} \cdot 3^{\max(1,2)} = 36
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, a mod b)gcd⁡(a,0)=a\gcd(a, b) = \gcd(b,\ a \bmod b) \qquad \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+ra = qb + r where r=a mod br = a \bmod b. Any number dd that divides both aa and bb also divides a−qb=ra - qb = r. And any dd that divides bb and rr also divides qb+r=aqb + r = a. So the pairs (a,b)(a, b) and (b,r)(b, r) have exactly the same common divisors, and therefore the same greatest one.

The Euclid loop

One comparison and one remainder per pass. The pair only ever gets smaller.

Worked example

gcd(48, 18) step by step

StepDivisionNew pair
148=18×2+1248 = 18 \times 2 + 12(18,12)(18, 12)
218=12×1+618 = 12 \times 1 + 6(12,6)(12, 6)
312=6×2+012 = 6 \times 2 + 0(6,0)(6, 0): stop, the GCD is 6
Three divisions. The last non-zero remainder, 6, is the GCD.

The pair shrinking

Each arrow is one loop pass: a, b = b, a % b.

Then the LCM

lcm⁡(48,18)=48gcd⁡(48,18)×18=486×18=144\operatorname{lcm}(48, 18) = \frac{48}{\gcd(48, 18)} \times 18 = \frac{48}{6} \times 18 = 144
Check: 6×144=864=48×186 \times 144 = 864 = 48 \times 18.

Geometry

GCD as the largest square tile

Picture a floor ww wide and hh tall. A square tile of side ss covers it exactly only if ss divides both ww and hh. The largest such tile has side gcd⁡(w,h)\gcd(w, h), and you need wg×hg\frac{w}{g} \times \frac{h}{g} of them. A 6×46 \times 4 floor takes six 2×22 \times 2 tiles; a 48×1848 \times 18 floor takes 8×3=248 \times 3 = 24 tiles of 6×66 \times 6.

Euclid with scissors

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)=∣a⋅b∣gcd⁡(a,b)=∣a∣gcd⁡(a,b)⋅∣b∣\operatorname{lcm}(a, b) = \frac{|a \cdot b|}{\gcd(a, b)} = \frac{|a|}{\gcd(a, b)} \cdot |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
  1. 1A leaves12, 24, 36, 48, ...
  2. 2B leaves18, 36, 54, ...
  3. 3gcd(12, 18) = 6Euclid: 18 → 12 → 6 → 0
  4. 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  ⇒  a mod b<a2a \ge b > 0 \;\Rightarrow\; a \bmod b < \frac{a}{2}
If b≤a2b \le \frac{a}{2}, the remainder is below b≤a2b \le \frac{a}{2}. If b>a2b > \frac{a}{2}, then a mod b=a−b<a2a \bmod b = a - b < \frac{a}{2}. Either way the remainder is under half of aa.

After two steps the pair (a,b)(a, b) becomes (a mod b,… )(a \bmod b, \dots), so the larger number at least halves every two steps. Halving can only happen about log⁡2\log_2 times, which gives at most about 2log⁡2min⁡(a,b)2 \log_2 \min(a, b) divisions. (After the first step the larger number is min⁡(a,b)\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))\gcd(F_{n+1}, F_n): \; 34 \to 21 \to 13 \to 8 \to 5 \to 3 \to 2 \to 1 \to 0 \qquad \text{steps} \le 5 \times (\text{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.
MethodTimegcd of two numbers near 10910^9
Try every divisor from min⁡(a,b)\min(a, b) downO(min⁡(a,b))O(\min(a, b))up to a billion checks
Prime factorisationslow for large numberstrial division up to n≈31,623\sqrt{n} \approx 31{,}623
Euclid, iterativeO(log⁡min⁡(a,b))O(\log \min(a, b)) time, O(1)O(1) spaceat most 43 divisions
Euclid, recursiveO(log⁡min⁡(a,b))O(\log \min(a, b)) time and stacksame count, plus call frames

In code

GCD and LCM in Python

Python
import mathfrom functools import reducedef gcd(a, b):    while b != 0:        a, b = b, a % b    return abs(a)def gcd_recursive(a, b):    return abs(a) if b == 0 else gcd_recursive(b, a % b)def lcm(a, b):    if a == 0 or b == 0:        return 0    return abs(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
LanguageGCDLCM
Python 3.9+math.gcd(*nums)math.lcm(*nums)
C++17std::gcd(a, b)std::lcm(a, b)
JavaBigInteger.gcd, or write the loopa / gcd(a, b) * b with long
JavaScriptwrite the loopa / 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)\gcd(a, b, c) = \gcd(\gcd(a, b), c), and the same for LCM.

Edge cases

Zero, negatives and coprimes

InputResultWhy
gcd⁡(0,15)\gcd(0, 15)15Every number divides 0, so the largest divisor of 15 wins
gcd⁡(0,0)\gcd(0, 0)0A convention; math.gcd(0, 0) returns 0
lcm⁡(0,b)\operatorname{lcm}(0, b)0Return 0 directly; the formula would divide by gcd⁡(0,0)=0\gcd(0, 0) = 0 when both are 0
gcd⁡(−12,18)\gcd(-12, 18)6The GCD is defined as positive; take abs or use math.gcd
gcd⁡(8,15)\gcd(8, 15)1Coprime: no shared prime factor, so lcm⁡=120=8×15\operatorname{lcm} = 120 = 8 \times 15
gcd⁡(n,n)\gcd(n, n), gcd⁡(1,n)\gcd(1, n)nn, 1A 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\exists\, x, y \in \mathbb{Z}: \quad a x + b y = \gcd(a, b) \qquad\text{e.g.}\quad 48 \cdot (-1) + 18 \cdot 3 = 6
The amounts you can make from steps of size aa and bb (forwards and backwards) are exactly the multiples of gcd⁡(a,b)\gcd(a, b). This is the whole idea behind the water jug puzzle.
Python
def ext_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?

Most number-theory warm-ups in interviews land in one of these four boxes.

Where it shows up

  • Fractions

    1218\frac{12}{18} reduces to 23\frac{2}{3} by dividing both by gcd⁡=6\gcd = 6. Adding fractions needs the LCM of the denominators.

  • Cryptography

    RSA picks an exponent coprime to φ(n)\varphi(n) and finds its inverse with extended Euclid.

  • Scheduling

    Jobs with periods 4, 6 and 10 all run together every lcm⁡=60\operatorname{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∣)\gcd(|s|, |t|).

  • Array rotation

    Rotating nn items by kk in place splits them into gcd⁡(n,k)\gcd(n, k) independent cycles.

Recap

Key takeaways

Key points

  • gcd⁡(a,b)\gcd(a, b) is the largest shared divisor; lcm⁡(a,b)\operatorname{lcm}(a, b) is the smallest shared multiple.
  • Euclid: gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b) until b=0b = 0. In code: a, b = b, a % b.
  • It works because (a,b)(a, b) and (b,a mod b)(b, a \bmod b) have exactly the same common divisors.
  • a mod b<a/2a \bmod b < a/2, so the work is O(log⁡min⁡(a,b))O(\log \min(a, b)); Fibonacci pairs are the worst case.
  • lcm⁡(a,b)=a/gcd⁡(a,b)×b\operatorname{lcm}(a, b) = a / \gcd(a, b) \times b, and gcd⁡×lcm⁡=a×b\gcd \times \operatorname{lcm} = a \times b.
  • Coprime means gcd⁡=1\gcd = 1. gcd⁡(n,0)=n\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.

Sources