GCD and Extended Euclid
a*x + b*y equal to that divisor.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.

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":
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:
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.