Divisibility and modular arithmetic
| Problem | Find greatest common divisors and Bézout coefficients, invert numbers and raise them to powers modulo , take exact integer square roots, and solve simultaneous congruences |
| Devised by | Euclid (c. 300 BC), the algorithm; Étienne Bézout (1779), the identity; Sunzi (3rd–5th century), the remainder theorem; Pingala (c. 200 BC), square-and-multiply; Newton’s method for square roots goes back to Heron |
| Accuracy | Exact integer arithmetic; agrees with SymPy on every reference case (see the chapter overview) |
| Cost | Euclid divisions; modular power multiplications; integer square root Newton steps; CRT merges |
| Read first | Nothing beyond the Preliminaries |
| API | gcd, extended_gcd, multiplicative_inverse_modulo, base_exponent_in_modulus, integer_square_root_newton, integer_square_root_binary_search, chinese_remainder |
Overview
Modular arithmetic works with remainders: when divides . Its basic tools are some of the oldest algorithms known. Euclid’s algorithm finds the greatest common divisor by repeated remainders. Its extended form also finds integers with , which give modular inverses. Square-and-multiply raises a number to a huge power modulo in a number of steps proportional to the exponent’s bit length. The Chinese remainder theorem combines congruences to different moduli into one. The integer square root completes the set; it underlies sieving and factoring. Together they are the arithmetic of public-key cryptography, error-correcting codes and hashing.
Where it is used
Modular arithmetic is clock arithmetic, and it runs much of the digital world.
- Cryptography. RSA and Diffie-Hellman use modular exponentiation and inverses of enormous numbers; the extended Euclidean algorithm computes the inverses.
- Error-correcting codes and hashing. Reed-Solomon codes and many hash functions work in finite fields built from modular arithmetic.
- Computer science. Hash tables, pseudo-random generators and calendar calculations.
- Signal processing. Number-theoretic transforms compute exact convolutions of integer sequences.
History
Euclid’s Elements (Book VII, c. 300 BC) gives the algorithm, the oldest still in everyday use. Indian mathematicians (Āryabhaṭa, c. 500) used its extension, the kuṭṭaka, to solve linear congruences, and Bézout (1779) proved the identity for polynomials. The problem of Sunzi’s Mathematical Classic (3rd–5th century) asks for a number leaving remainders 2, 3 and 2 on division by 3, 5 and 7. Qin Jiushao (1247) gave the general method, and Gauss’s Disquisitiones Arithmeticae (1801) put congruences on their modern footing. Gabriel Lamé (1844) proved one of the first complexity bounds of any algorithm: Euclid needs at most about five times as many steps as the smaller number has decimal digits. In 1977 Rivest, Shamir and Adleman built RSA from exactly these tools.
The idea
Euclid’s algorithm and Bézout coefficients
The greatest common divisor. The gcd of two integers is the largest integer dividing both. Factorising them is a hopelessly slow way to find it. Euclid’s algorithm rests instead on one observation: any number that divides both and also divides the remainder , and conversely any number that divides and the remainder divides . So the pair has the same common divisors as the pair :
The new pair is smaller. Repeating until the remainder is zero leaves the gcd. For 252 and 198:
so , the last nonzero remainder.
Bézout coefficients. The gcd can always be written as a combination of the two numbers, with integers and . Working backwards through the example, , so . The extended Euclidean algorithm finds and in the forward pass, without backtracking: it carries along, for each remainder, a pair of coefficients that express it as a combination of and , updating them by the same rule as the remainders. The last nonzero remainder then arrives with its coefficients. These coefficients are what make division possible in modular arithmetic (next section).
How many steps? Each remainder is less than half the number two steps before it, so the number of steps is proportional to the number of digits. The worst case is a pair of consecutive Fibonacci numbers, where every quotient is 1 and the numbers shrink as slowly as possible (Lamé). Random inputs need about steps (Heilbronn, 1969):
Figure 22.1. Euclid steps.
Inverses and powers
Modular arithmetic. Two integers are congruent modulo , written , if they leave the same remainder on division by . Sums, differences and products can be computed on remainders alone, like arithmetic on a clock face with hours.
Division is the subtle operation. The inverse of modulo is a number with
; dividing by means multiplying by . It exists exactly when
, and the extended Euclidean algorithm finds it: if , then reducing
both sides modulo leaves . For example, , so the
inverse of 3 modulo 7 is 5. multiplicative_inverse_modulo returns the inverse in
, or an error if none exists.
Powers. Cryptography needs with exponents of hundreds of digits, so multiplying times is out of the question, and so is computing before reducing. Square-and-multiply uses the binary digits of . Repeated squaring gives , each reduced modulo , and is the product of those whose bit in is 1. To compute , with :
That takes multiplications, and no number ever exceeds . Products of residues
below fit in 128 bits when . For larger moduli the library multiplies by
double-and-add (the same idea applied to multiplication), so every positive i128 modulus works.
Integer square roots
is needed exactly, which floating point cannot guarantee beyond . Newton’s iteration , started at a power of two above , decreases monotonically to and stops when an iterate fails to decrease. Started below the root, the integer iteration can instead alternate between and forever, as the library’s original version did. Bisection is the slower, simpler alternative.
The Chinese remainder theorem
A number is determined by its remainders. If the moduli are pairwise coprime, the system has exactly one solution modulo the product . The classical example asks for a number that leaves remainder 2 on division by 3, 3 on division by 5 and 2 on division by 7. The first two conditions are met by 8, and by every number congruent to 8 modulo 15. Among the first with remainder 2 on division by 7 is 23, and the general solution is .
The library solves the system the same way, merging congruences one at a time. Suppose the congruences so far are summarised as , and the next is . Every candidate has the form , and the new condition is a linear congruence for , solved with a modular inverse. If and share a factor , the congruences are consistent only if divides ; the merged modulus is then . So moduli that are not coprime are handled too.
With , , and , the extended Euclidean algorithm gives , so . The message 4242424242 encrypts to 128943449465725493 and decrypts back to 4242424242.
Algorithm
Extended Euclidean algorithm, for integers and . It keeps two rows , each satisfying .
- Initialise the rows to and . Both satisfy the relation.
- While the second row’s is not zero: compute the quotient of the first row’s by the second’s; form a new row as the first minus times the second (in all three entries); discard the first row, so that the second becomes the first and the new row the second. A combination of two rows that satisfy the relation satisfies it too.
- When the second row’s is zero, the first row holds and its Bézout coefficients. If the gcd came out negative, change the sign of the whole row.
The number of iterations is proportional to the number of digits of the smaller input.
Modular inverse of modulo : run the extended algorithm on and . If the gcd is not 1 there is no inverse. Otherwise the coefficient , reduced into , is the inverse.
Modular power :
- set the result to 1 and the base to ;
- while : if the lowest bit of is 1, multiply the result by the base, modulo ; square the base, modulo ; shift right by one bit.
Integer square root of : start with equal to a power of two above ; repeat ; if , return ; otherwise set .
Chinese remainder theorem, for a list of congruences. Start with the solution modulo . For each congruence :
- compute ; if does not divide , the system has no solution;
- solve for , with a modular inverse;
- replace by and by , and reduce into .
Implementation
while r != 0 {
let quotient = old_r / r;
let temp_r = old_r - quotient * r;
old_r = r;
r = temp_r;
let temp_s = old_s - quotient * s;
old_s = s;
s = temp_s;
let temp_t = old_t - quotient * t;
old_t = t;
t = temp_t;
}
while exp > 0 {
// If the current exponent bit is set, multiply result by base
if exp & 1 == 1 {
result = mul_mod_u128(result, base, m);
}
// Square the base and reduce modulo
base = mul_mod_u128(base, base, m);
// Shift exponent right by one bit
exp >>= 1;
}
let bits = 128 - n.leading_zeros();
let mut x = 1u128 << bits.div_ceil(2);
loop {
let next = (x + n / x) / 2;
if next >= x {
return x;
}
x = next;
}
for (&r, &mi) in residues.iter().zip(moduli) {
let r = r.rem_euclid(mi);
// Merge x (mod m) with r (mod mi): x + m t ≡ r (mod mi), i.e. m t ≡ r − x (mod mi).
let (g, p, _) = extended_gcd(m, mi);
let difference = r - x;
if difference % g != 0 {
return Err(ErrorsJSL::InvalidInputRange("The congruences are inconsistent."));
}
let step = mi / g;
// t = (difference / g) · p (mod mi / g), with p the inverse of m/g modulo mi/g.
let t = ((difference / g) % step * (p % step)).rem_euclid(step);
let lcm = m.checked_mul(step).ok_or(ErrorsJSL::InvalidInputRange("The combined modulus overflows."))?;
x = (x + m.checked_mul(t).ok_or(ErrorsJSL::InvalidInputRange("The combined modulus overflows."))?).rem_euclid(lcm);
m = lcm;
}
- Arguments are
i128(gcd, inverses, powers, CRT) oru128(square roots); the GCD is never negative.
In practice
//! Modular arithmetic: gcd, Bézout coefficients, inverses, powers, integer square roots and the
//! Chinese remainder theorem, ending with a toy RSA key.
use lib_jsl_number_theory::base_exponent_in_modulus::base_exponent_in_modulus;
use lib_jsl_number_theory::chinese_remainder_theorem::chinese_remainder;
use lib_jsl_number_theory::greatest_common_divisor::{extended_gcd, gcd};
use lib_jsl_number_theory::integer_square_root::integer_square_root_newton;
use lib_jsl_number_theory::multiplicative_inverse_modulo::multiplicative_inverse_modulo;
fn main() {
println!("gcd(1071, 462) = {}", gcd(1071, 462));
let (g, x, y) = extended_gcd(240, 46);
println!("240·({x}) + 46·({y}) = {g}");
println!("17⁻¹ mod 3120 = {}", multiplicative_inverse_modulo(17, 3120).unwrap());
println!("2^1000 mod 1000000007 = {}", base_exponent_in_modulus(2, 1000, 1_000_000_007).unwrap());
println!("⌊√(10^30 + 1)⌋ = {}", integer_square_root_newton(10u128.pow(30) + 1));
// x ≡ 2 (mod 3), x ≡ 3 (mod 5), x ≡ 2 (mod 7), the problem of Sunzi.
let (x, m) = chinese_remainder(&[2, 3, 2], &[3, 5, 7]).unwrap();
println!("Sunzi: x ≡ {x} (mod {m})");
// Toy RSA: n = p q, d = e⁻¹ mod (p − 1)(q − 1).
let (p, q, e) = (61i128, 53i128, 17i128);
let (n, phi) = (p * q, (p - 1) * (q - 1));
let d = multiplicative_inverse_modulo(e, phi).unwrap();
let c = base_exponent_in_modulus(65, e, n).unwrap();
println!("RSA with n = {n}, e = {e}, d = {d}: 65 → {c} → {}", base_exponent_in_modulus(c, d, n).unwrap());
}
gcd(1071, 462) = 21
240·(-9) + 46·(47) = 2
17⁻¹ mod 3120 = 2753
2^1000 mod 1000000007 = 688423210
⌊√(10^30 + 1)⌋ = 1000000000000000
Sunzi: x ≡ 23 (mod 105)
RSA with n = 3233, e = 17, d = 2753: 65 → 2790 → 65
Strengths
- Exact, fast and overflow-safe within
i128; the CRT accepts non-coprime moduli and reports inconsistency.
Weaknesses
- Fixed-width integers: no arbitrary-precision moduli (see the decimal-string integers for unbounded but slow arithmetic).
- Not constant-time, so unsuitable for cryptography where timing leaks matter.
Exercises
- Prove that , and that the extended algorithm’s invariant holds at every step.
- Show that Euclid’s algorithm on consecutive Fibonacci numbers takes the most steps for inputs of their size, and derive Lamé’s bound.
- Compute by hand with square-and-multiply.
- Show that the integer Newton iteration started above decreases monotonically to , and find a starting point below the root from which it cycles.
- Solve , , and explain why the answer is unique modulo 12, not 24.
Hints and answers
- If and then , and conversely, so the common divisors of and coincide. For the invariant: initially and ; each step subtracts times one equation from the other, preserving the form.
- If the algorithm takes steps, the smaller input is at least ; Fibonacci numbers are the smallest inputs that need that many steps because every quotient is 1. Since , the number of steps is at most about (Lamé).
- , , , , (mod 1000), and .
- Let . By AM-GM , and while the step decreases , so it descends monotonically. For starting from the iteration jumps back above the root, which is how a cycle arises.
- and are compatible because . The solution is : unique modulo , not , because the moduli share the factor 2.
Further reading
- D. E. Knuth, The Art of Computer Programming, vol. 2, Seminumerical Algorithms, 3rd ed., Addison-Wesley, 1997, sections 4.5.2–4.6.3.
- V. Shoup, A Computational Introduction to Number Theory and Algebra, 2nd ed., Cambridge University Press, 2009, chapters 1–4.
- R. L. Rivest, A. Shamir and L. Adleman, “A method for obtaining digital signatures and public-key cryptosystems”, Communications of the ACM 21 (1978) 120–126.