← LibraryEuclid's Algorithm and Modular ComputationEngineering · MathematicsLesson 23/32← PrevNext →
ArticlePublished 6 Aug 2026Updated 5 Aug 20269 min readBy Kevin Jogin
KEVOS® Knowledge Library · Engineering → Mathematics

Engineering/Mathematics/Algorithm engineering

Euclid's Algorithm and Modular Computation

One two-thousand-year-old algorithm computes greatest common divisors, modular inverses, Chinese remainder coefficients, rational reconstructions and Reed–Solomon error locators. Learning where the extended Euclidean algorithm is hiding is one of the highest-leverage moves in computational algebra.

  • Core algorithm
  • Computing
  • Reused everywhere
  • ≈17 min read
  • Enables RSA key setup
O(ℓ²)CostBit operations for -bit inputs: O(ℓ) division steps of O(ℓ) each.
≤ 4.8·log₁₀Lamé's boundThe number of division steps is at most about 4.8 times the number of decimal digits — worst case at consecutive Fibonacci numbers.
s·a + t·bBézout outputThe extended version returns the certificate, which is what makes it an inversion algorithm.
4× fasterCRT in RSARecombining two half-size exponentiations is the single largest constant-factor gain in RSA private operations.

01

Executive summary

The Euclidean algorithm replaces the pair (a,b) by (b, a mod b) until the second entry is zero; the surviving value is the gcd. The extended version carries a pair of coefficients along, so that at termination it also reports s,t with sa + tb = gcd(a,b).

That certificate is what makes the algorithm ubiquitous. Setting b = n and gcd = 1 gives a modular inverse. Running it on polynomials gives inverses in F[X]/(f), hence finite field arithmetic. Stopping it early, rather than running to completion, solves rational reconstruction and decodes Reed–Solomon codes.

Base algorithmgcd(a,b)

Repeated remaindering; O(ℓ) steps by a Fibonacci-worst-case argument.

ExtendedBézout coefficients

Carries the linear combination; same asymptotic cost.

SpecialisationModular inverse

gcd(a,n)=1 gives a^{-1} ≡ s (mod n).

Early stoppingRational reconstruction

Halting mid-run yields the best rational approximation with bounded numerator and denominator.

Contents

02

The basic algorithm and its analysis

Euclidean algorithm

  1. input: integers a, b ≥ 0
  2. while b ≠ 0: (a, b) ← (b, a mod b)
  3. return a

O(ℓ) iterations on ℓ-bit inputs, each a division costing O(ℓ) word operations — O(ℓ²) bit operations overall.

Theorem T1

Lamé's theorem

The number of division steps for inputs a > b > 0 is at most logφ(√5·b) ≈ 4.785·log10 b + 1.67, where φ is the golden ratio, and this is attained exactly when a and b are consecutive Fibonacci numbers. The heuristic reason: each step reduces the pair by at least a factor of φ on average, and a run of small quotients is the worst case.

  • Average behaviour is better than worst case. The average number of steps is about (12 ln 2/π2)·ln b ≈ 0.843·ln b, a result of Heilbronn and Dixon; quotients follow the Gauss–Kuzmin distribution, with quotient 1 occurring about 41% of the time.
  • Binary gcd replaces division with subtraction and shifts. It performs more iterations but each is far cheaper on hardware without a fast divider, and it is often the practical winner for word-size and moderate operands.
  • Subquadratic gcd exists — Schönhage's half-gcd runs in Õ(ℓ) — but crossover occurs only at tens of thousands of bits, well above cryptographic operand sizes.
Contents

03

The extended Euclidean algorithm

Extended Euclidean algorithm

  1. input: a, b ≥ 0
  2. (r₀, s₀, t₀) ← (a, 1, 0); (r₁, s₁, t₁) ← (b, 0, 1)
  3. while r₁ ≠ 0:
  4. q ← ⌊r₀ / r₁⌋
  5. (r₀, r₁) ← (r₁, r₀ − q·r₁)
  6. (s₀, s₁) ← (s₁, s₀ − q·s₁)
  7. (t₀, t₁) ← (t₁, t₀ − q·t₁)
  8. return (r₀, s₀, t₀) // r₀ = gcd(a,b) = s₀·a + t₀·b

Same O(ℓ²) as the basic version. The invariant s_i·a + t_i·b = r_i holds at every step, and the coefficients stay bounded: |s_i| ≤ b/(2·gcd) and |t_i| ≤ a/(2·gcd).

Modular inversion

Run the algorithm on (a, n). If the gcd is 1, then s·a + t·n = 1, so s ≡ a−1 (mod n) after reduction to [0,n). If the gcd exceeds 1, no inverse exists — and the gcd itself is a non-trivial factor of n, which some factoring algorithms deliberately provoke.

Inversion strategies compared
MethodCostConstant time?Use case
Extended EuclidO(ℓ2)No — branch pattern depends on inputsGeneral purpose, public data
Binary extended gcdO(ℓ2), better constantsNo, without careSoftware without fast division
Fermat: ap−2 mod pO(ℓ3)Yes, with a fixed exponentiation ladderSecret data in prime fields
Batch inversion (Montgomery's trick)one inversion + 3(k−1) multiplicationsInherits from the single inversionInverting k elements at once, as in elliptic curve batch operations
Constant-time divstepO(ℓ2), fixed iteration countYes by constructionModern cryptographic libraries

Montgomery's batch trick: compute running products, invert the total once, then walk backwards recovering each inverse with two multiplications.

Do not use plain extended Euclid on secret values

The iteration count and quotient sizes depend on the operands, which leaks timing information about a secret. Where an inverse of secret data is required, use a fixed-iteration algorithm — exponentiation by p−2, or a constant-time divstep variant with a proven iteration bound.

Contents

04

Chinese remaindering in practice

Given residues ai modulo pairwise coprime ni, reconstruction produces the unique x modulo n = ∏ ni. Two schemes are standard.

CRT reconstruction schemes
SchemeFormulaCostBest for
Gauss / directx = ∑ ai·(n/ni)·[(n/ni)−1 mod ni]O(k) inverses, then full-size arithmeticFixed moduli reused many times — precompute the coefficients
Garner / incrementalmixed-radix, one modulus at a timeAll arithmetic stays small until the final assemblyStreaming or memory-constrained settings
Divide and conquerproduct tree plus remainder treeÕ(ℓ) for many moduliHundreds or thousands of small moduli

RSA private operation via CRT

  1. precompute: d_p = d mod (p−1), d_q = d mod (q−1), q_inv = q^{-1} mod p
  2. m_p ← c^{d_p} mod p
  3. m_q ← c^{d_q} mod q
  4. h ← q_inv·(m_p − m_q) mod p
  5. m ← m_q + h·q
  6. verify m^e ≡ c (mod n) before releasing // fault-attack countermeasure

Two exponentiations at half the bit length: roughly a fourfold speed-up under a cubic cost model. The verification step costs one cheap public-exponent operation and is not optional.

The Bellcore fault attack

If a hardware fault corrupts exactly one of the two half-exponentiations, then gcd(me − c, n) reveals a prime factor of n. A single faulty signature is enough. Verifying the result before release, or computing both halves twice and comparing, closes this. Any CRT-RSA implementation without such a check should be treated as broken.

Contents

05

Speeding up algorithms via modular computation

Exact computation over or suffers from intermediate expression swell: entries in a matrix elimination, or coefficients in a polynomial gcd, grow far beyond the size of the input and output. The remedy is to compute modulo several small primes and reconstruct.

  1. Bound the output

    Derive an a priori bound H on the size of the answer — Hadamard's bound for determinants, Mignotte's bound for polynomial factors, or a direct size estimate.

  2. Choose enough small primes

    Pick word-size primes with product exceeding 2H, avoiding any prime that divides a leading coefficient or otherwise degrades the problem.

  3. Solve modulo each prime

    Each subproblem uses single-word arithmetic and is independent of the others, so the stage parallelises perfectly.

  4. Reconstruct by CRT

    Combine the modular images into a residue modulo the product of the primes.

  5. Recover the integer or rational

    Interpret the residue as a signed integer, or apply rational reconstruction if the true answer is a fraction.

  6. Verify

    Check the reconstructed answer against the original problem; this converts a probabilistic method into a certified one at low cost.

Where multi-modular computation pays off
ProblemNaive approachModular approach
Determinant of an integer matrixFraction-free elimination with growing entriesModular determinants plus CRT, using Hadamard's bound
Polynomial gcd over ℤ[X]Coefficient explosion in the subresultant algorithmgcd modulo several primes, CRT, then a divisibility check
Linear system over Exact rational eliminationSolve modulo primes, then rational reconstruction
Big-integer convolutionDirect multiplicationMultiply modulo several primes and recombine

This is the same principle as the CRT speed-up in RSA — replace one big computation by several small independent ones — applied to symbolic computation instead of cryptography.

Contents

06

Rational reconstruction

Theorem T2

Rational reconstruction

Given z and modulus n, and bounds r*, t* > 0 with 2r*t* ≤ n, there is at most one pair (r,t) with |r| ≤ r*, 0 < t ≤ t*, gcd(t,n) = 1 and r ≡ zt (mod n). It is found by running the extended Euclidean algorithm on (n, z) and stopping at the first remainder below r*.

The algorithm is the ordinary extended gcd with a different stopping rule. Its intermediate values are exactly the convergents of the continued fraction expansion of z/n, which is why continued-fraction and Euclidean treatments of these problems coincide.

01

Exact rational answers

Recover a fraction from its image modulo n — the final step of multi-modular linear algebra over .

02

Reed–Solomon decoding

The error locator and evaluator polynomials are a rational reconstruction of the syndrome polynomial, with degree bounds replacing size bounds.

03

Wiener's attack on RSA

A small private exponent d < n1/4/3 is recovered by reconstructing k/d from e/n — a direct application, and the reason small private exponents are forbidden.

04

Sequence and recurrence recovery

The polynomial version reconstructs the minimal polynomial of a linearly generated sequence, powering Wiedemann's algorithm.

The unifying view

Run the extended Euclidean algorithm and stop early: the remainder r and multiplier t at that point form the best rational approximation subject to the size constraint. Everything in the four cards above is that one sentence, instantiated in a different ring with a different notion of size.

Contents

07

Quick reference and FAQ

Costs and bounds
QuantityValue
gcd, extended gcdO(ℓ2) bit operations
Worst-case iteration count≈ 4.785·log10 b (consecutive Fibonacci inputs)
Average iteration count≈ 0.843·ln b
Bézout coefficient sizes|s| ≤ b/(2g), |t| ≤ a/(2g)
Modular inverseone extended gcd; fails only when gcd > 1
CRT for k moduliO(k2) small operations, or Õ(ℓ) with a product tree
Rational reconstruction condition2r*t* ≤ n guarantees uniqueness
RSA CRT speed-up≈ 4× for the private operation
Does the Euclidean algorithm ever fail or loop?
No. Remainders strictly decrease and are non-negative, so termination is guaranteed. The only implementation pitfalls are negative inputs and the language-dependent sign of the remainder operator.
Why does the extended version cost no more asymptotically?
The coefficient updates are one multiplication and one subtraction per iteration, with operands bounded by the original inputs. The iteration count is unchanged, so the asymptotic cost is the same — typically a factor of two to three in practice.
When should the binary gcd be preferred?
When division is expensive relative to shifting and subtraction, which is common on embedded targets, and for operands of a few words. For very large operands the division-based version wins because each step makes more progress.
Is rational reconstruction the same as continued fractions?
The computations coincide: the extended Euclidean algorithm's intermediate results are the continued fraction convergents. Rational reconstruction is the algorithmic packaging with explicit bounds and a stopping rule, which is what makes it directly usable.
Contents

09

References and further reading

  • V. Shoup, A Computational Introduction to Number Theory and Algebra, Cambridge University Press, 2005 — Chapter 4.
  • D. E. Knuth, The Art of Computer Programming, Vol. 2, 3rd ed., Addison-Wesley, 1997 — §4.5.2 and §4.5.3.
  • D. Boneh, R. A. DeMillo and R. J. Lipton, 'On the importance of checking cryptographic protocols for faults', EUROCRYPT '97, LNCS 1233, 37–51.
  • M. Wiener, 'Cryptanalysis of short RSA secret exponents', IEEE Trans. Inform. Theory 36 (1990) 553–558.
  • D. J. Bernstein and B.-Y. Yang, 'Fast constant-time gcd computation and modular inversion', IACR TCHES 2019(3), 340–398.

KEVOS® Knowledge LibraryEngineering → MathematicsTaxonomy ID: ENG-MATHPage ID: euclidean-algorithm-and-modular-computationReview cycle: annual


Continue learning

Multiprecision Integer ArithmeticArticle · MathematicsNEXT LESSON →Probabilistic AlgorithmsArticle · MathematicsAsymptotic Notation and Machine ModelsArticle · MathematicsProbabilistic Primality TestingArticle · Mathematics