Skip to the workspace
Pebellslearn by building
Bits & Machine Numbers  ›  Lesson

GCD and Extended Euclid

GCD & Extended Euclid 28 minEuclid's remainders keep a receipt of how to build them, and that receipt is the modular inverse

dsa / GCD and Extended Euclid

Explore each scene at your own pace.

01 · Euclid's algorithm

Euclid's algorithm

GCD and Extended Euclid

Definition
Euclid's algorithm finds the greatest common divisor of two integers by repeatedly replacing the pair (a, b) with (b, a mod b) until the second is 0, and the extended version also finds integers x and y with a*x + b*y equal to that divisor.
In plain words
To find the biggest tile that exactly fits two lengths, keep replacing the longer length with what is left over after fitting the shorter one in. When nothing is left over, the last length is the answer, and tracking the steps lets you work backwards.

In short: Euclid's algorithm replaces (a, b) with (b, a % b) until b is 0, because both pairs share the same common divisors, and that pair shrinks fast enough to finish in O(log min(a, b)) time and O(1) space. Run the same replacement on two tracked coefficients (extended Euclid) and you get Bézout's identity a·x + b·y = gcd(a, b) for free, which gives a's modular inverse whenever gcd(a, m) = 1 — exactly the tool for undoing a multiply modulo m.

Four boxes (48,18) -> (18,12) -> (12,6) -> (6,0) connected by arrows labelled a % b, with the last box highlighted green as the gcd

Quarry shows record ids to the outside world in URLs and API responses. Sequential ids leak information. If yesterday's record was 1,000 and today's is 1,850, anyone can see how fast your data is growing. The usual cure is to scramble each id before showing it. Multiply it by a secret key modulo 2³², which in a 32-bit word is just "multiply and let it wrap":

python

The public ids look random. But Quarry needs the real id back when a URL comes in, so it has to undo a multiplication modulo 2³². That needs a number INV with KEY · INV ≡ 1 (mod 2³²), the key's modular inverse. The algorithm that finds it is more than two thousand years old and still runs in O(log m) steps. It also answers whether an inverse exists at all.

Euclid's algorithm

The greatest common divisor gcd(a, b) is the largest number dividing both. Euclid's observation: any number that divides both a and b also divides a − q·b for any q, and in particular a % b. So the pairs (a, b) and (b, a % b) have exactly the same common divisors. Keep replacing the pair until the second number is 0. The first number is then the gcd:

python
What does this print?
a, b, steps = 1234, 322, 0
while b:
    a, b = b, a % b
    steps += 1
print(a, steps)

Why so few steps? After two iterations the larger number has at least halved: if b ≤ a/2 then a % b < b ≤ a/2, and otherwise a % b = a − b < a/2. So the loop is O(log min(a, b)). The worst case is two consecutive Fibonacci numbers, where every quotient is 1 and the numbers shrink as slowly as possible. Even then it takes only about log base φ of n steps, where φ ≈ 1.618:

digits in n worst-case steps
5 24
10 48
20 96
21 100.5

Each extra decimal digit costs fewer than 5 more steps, so numbers up to 20 digits never need more than 100. Quarry's 32-bit keys have at most 10 digits, so the loop never runs more than about 48 times.

Scene 1 of 7
Project context and further resources
You're building a piece ofQuarry — the record encoder
This piece — mod_inverse(): Undoes the multiply that hides sequential record ids, using an inverse from extended Euclid.
Scenario Quarry never shows sequential ids to the outside world. It multiplies each by a secret odd key mod 2³². When a URL comes back in, the id scrambler multiplies by the key's inverse, computed once with extended Euclid, and the real record id reappears.
mod_inverse.py
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.