Number-Theoretic Algorithms
Number-theoretic algorithms work with integers, divisibility, congruences, primes, and modular arithmetic. They appear in cryptography, hashing, coding theory, randomized algorithms, and many programming problems.
Greatest Common Divisor
The Euclidean algorithm uses the identity:
gcd(a,b):
while b != 0:
(a,b) = (b, a mod b)
return |a|Its running time is O(log min(a,b)) arithmetic iterations.
Extended Euclidean Algorithm
The extended version computes integers x and y such that:
This Bézout identity is the standard tool for computing modular inverses when they exist.
Modular Arithmetic
Two integers are congruent modulo m when they leave the same remainder:
- (a+b) mod m can be reduced componentwise.
- (ab) mod m can be reduced componentwise.
- Subtraction may require normalization to keep a non-negative representative.
Fast Modular Exponentiation
Exponentiation by squaring computes a^n mod m using O(log n) multiplications.
powmod(a,n,m):
result = 1
a = a mod m
while n > 0:
if n is odd:
result = result*a mod m
a = a*a mod m
n = floor(n/2)Primality Testing
Trial division only needs to test possible factors up to √n, giving O(√n) divisibility checks.
For large integers, probabilistic tests such as Miller–Rabin are far more practical. Deterministic variants exist for bounded integer ranges.
Modular Inverse
An inverse of a modulo m is a value x satisfying:
Such an inverse exists iff gcd(a,m)=1.
The Extended Euclidean Algorithm works for any coprime a and m.
Fermat's Little Theorem
If p is prime and p does not divide a:
Therefore, for prime p and a not divisible by p:
This is why fast exponentiation can compute inverses efficiently under a prime modulus.
Chinese Remainder Theorem
For pairwise coprime moduli, a system of congruences has a unique solution modulo the product of the moduli.
CRT is useful for reconstruction, cryptography, modular computation, and splitting large arithmetic into smaller independent pieces.
Sieve of Eratosthenes
To list all primes up to n, mark multiples of each discovered prime.
The classic sieve runs in O(n log log n) time and O(n) space.
Algorithmic Applications
- Public-key cryptography
- Hash functions and rolling hashes
- Modular combinatorics
- Randomized primality testing
- Checksums and coding theory
- Fast recurrence computation