Number Theory: GCD & Modular Arithmetic
This lesson opens the mathematical-algorithms module with the bedrock of computational number theory. We prove Euclid's recurrence and its running time, extend it to recover Bézout coefficients with , and build modular arithmetic on residue classes — including when a modular inverse exists and how to compute it.
╌╌╌╌
Most of this course has measured algorithms against the size of their input:
elements, vertices, levels of a tree. Number-theoretic algorithms
break that habit. Their inputs are single integers, and the interesting cost is
measured against the magnitude of those integers, or equivalently the number
of bits needed to write them down. The oldest non-trivial algorithm we know,
Euclid's, from around 300 BCE, belongs to this family, and it is still the right way to
compute a greatest common divisor. This lesson develops it carefully, extends it
to solve linear Diophantine equations, and uses both to lay the foundations of
modular arithmetic, the arithmetic that underlies hashing, cryptography, and
the math
problems you will meet in practice.
Divisibility and the greatest common divisor
For integers and we say divides (written ) if for some integer . A common divisor of and is an integer dividing both. The greatest common divisor is the largest such integer, with the conventions and . Throughout we take ; signs only flip the answer's sign.1
The naive way to compute , factoring both numbers and multiplying the shared prime powers, is a mistake: integer factorization is believed to be hard, and the sieve and factorization methods that find those prime powers are themselves a separate study. Euclid's insight is that the factorization is never needed.
Euclid's algorithm
The entire algorithm rests on one recurrence.
The base case is immediate: every integer divides , so the largest divisor of and is itself. The recurrence follows from a sharper claim: the two pairs share exactly the same set of common divisors, hence the same greatest one.
Because the second argument strictly shrinks () and stays non-negative, the recursion must terminate, and it terminates at a pair whose answer is .
- 1while do
- 2
- 3
- 4
- 5return
Why it is fast
Each iteration replaces with . The key fact is that two iterations at least halve the larger argument.
So after every two steps the first argument drops below half its value; the number of iterations is therefore once the first swap orders the arguments.2 Each iteration does one division on numbers of bits, so the bit-complexity is polynomial in the input size, exponentially better than factoring. (For a refresher on this kind of logarithmic bound, see asymptotic analysis.)
The worst case is slow precisely because every quotient is the smallest it can be, , so each step subtracts only once and the pair merely slides to the previous Fibonacci pair. A single larger quotient would collapse the chain far faster.
Each iteration simply replaces the pair by and recurses; tracing shows the second argument collapsing to in three steps.
Euclid, geometrically
Replacing by repeated subtraction gives the subtractive form of the algorithm, and it has a geometric reading: tile an rectangle greedily with the largest squares that fit. Cut off a square as many times as you can, then recurse on the leftover strip. The side of the last square is the gcd.
Extended Euclid: Bézout's identity
Euclid tells us what the gcd is; the extended algorithm tells us how to build it out of and .
So the back-substitution recurrence is
- 1if then
- 2return
- 3
- 4
- 5
- 6return
It performs the same divisions as plain Euclid, so it is also . The table below traces : the forward pass fills the remainder/quotient columns top-down, and the coefficients are filled bottom-up by the back-substitution recurrence, landing on Bézout coefficients for the original pair in the top row.
When does have a solution?
Bézout characterizes exactly when the general linear Diophantine equation is solvable.
This is the predicate behind the Water and Jug Problem (can we measure liters using jugs of capacity and ? iff and ) and Check if Point Is Reachable, where the reachable lattice is governed by the gcd of the allowed steps.
Modular arithmetic
Fix a modulus . We say is congruent to modulo , written
i.e. and leave the same remainder on division by . Congruence is an
equivalence relation, and it partitions the integers into residue classes. The decisive property is that the class operations are
well-defined: if and , then
So you may reduce mod at any point in a chain of , , without
changing the final residue, the foundation of every answer modulo
problem and of combinatorics modulo a prime.3
When two coprime moduli are at play, the residue classes interlock perfectly: the pair pins down uniquely modulo . The grid below tabulates that bijection, with landing in each cell, the constructive heart of the Chinese Remainder Theorem we revisit in combinatorics.
Modular inverse and linear congruences
A modular inverse of modulo is an integer with
. It is what lets you divide
by .
There are two standard ways to produce the inverse:
- Extended Euclid. Run to get . Reducing mod kills the term, leaving , so is the inverse. This works for any coprime modulus and costs .
- Fermat's little theorem. When is prime, every is coprime to , and , hence . Computed by fast exponentiation in multiplications, the subject of the next lesson, on modular exponentiation and primality.
The reason an inverse exists exactly when is visible directly: multiplying every nonzero residue by such an permutes them, so some residue must land on , and that residue is . Below, multiplying by modulo shuffles the set, and the arrow into comes from , so .
- 1
- 2if then
- 3return "no inverse"not coprime
- 4returnnormalize into
The same machinery solves the general linear congruence . Let .
When this reduces to multiply both sides by
and yields the
single solution , the everyday case. The general count
applies when the modulus and coefficient share a factor.
Worked example (a linear congruence with a shared factor). Solve . Here , , , and . Since divides , the congruence is solvable, and the theorem promises exactly solutions modulo . Divide the whole congruence through by : with , , we solve . The inverse (from the permutation figure above), so . Lifting back to modulus , the two solutions are and and . Checking: and , both correct.
GCD refinements and where Bézout matters
Euclid's algorithm is the oldest non-trivial algorithm in continuous use, and the modern refinements of it are worth knowing.
Binary GCD (Stein's algorithm). Division is expensive on hardware that lacks a fast divide, and each Euclid step needs a modulo. In 1967 Josef Stein published a variant that uses only subtraction, comparison, and shifts — no division at all.4 It rests on three facts: (pull out a common factor of two), when is odd (a factor of two in one argument alone is irrelevant to an odd gcd), and for odd. Stripping factors of two is a single shift instruction, so binary GCD is often faster in practice than Euclid despite touching the same number of bits. On : pull out one common to reach ; is even and odd, so drop that factor to , then ; both odd now, subtract to .
Bit complexity, done honestly. Counting each division as one step gives operations, but on numbers of bits, one schoolbook division already costs bit operations, so Euclid is bit operations in the naive accounting. The half-GCD algorithm, using fast multiplication, computes a gcd in bit operations by a Knuth–Schönhage divide-and-conquer that processes the high-order bits in one batch,5 the same asymptotic class as multiplication itself. This is what large-integer libraries (GMP) actually run for big inputs.
Where Bézout coefficients matter. The extended algorithm's
coefficients serve directly as the modular inverse (), the CRT
reconstruction weights, and the private exponent in RSA key generation ( is one extended-Euclid call). Every time a cryptographic
library inverts modulo the group order,
it is running the algorithm on this page.
Takeaways
- is computed by Euclid's algorithm via , base ; the recurrence is exact because and have identical common divisors.
- Euclid runs in iterations because two steps at least halve the argument; the worst case is consecutive Fibonacci numbers.
- Extended Euclid returns Bézout coefficients with , and is solvable iff , the test behind Water-and-Jug and Check-if-Point-Is-Reachable.
- Modular arithmetic is arithmetic on residue classes; are well-defined, but division requires an inverse and overflow must be guarded.
- A modular inverse exists iff , found by extended Euclid, or by Fermat () when is prime; the linear congruence is solvable iff , with exactly solutions.
Footnotes
- CLRS, Ch. 31 — Number-Theoretic Algorithms (§31.1–31.2): divisibility, common divisors, and the recursive characterization of the gcd. ↩
- CLRS, Ch. 31 — Number-Theoretic Algorithms (§31.2): Euclid's and the extended algorithm; the Fibonacci worst case bounds the iteration count to . ↩
- Skiena, § — Number Theory: residue classes, congruences, and practical modular-arithmetic pitfalls (overflow, negative remainders). ↩
- J. Stein,
Computational problems associated with Racah algebra,
Journal of Computational Physics 1(3), 1967 — the binary (shift-and-subtract) GCD; see also Knuth, The Art of Computer Programming, Vol. 2 §4.5.2. ↩ - Knuth, The Art of Computer Programming, Vol. 2 §4.5.2 (the half-GCD / Schönhage recursion): a gcd in bit operations via fast multiplication. ↩
╌╌ END ╌╌