Algorithms · Visualized
Number Theory
Number Theory
Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.
Big-O: GCD O(log min(a,b)); sieve O(n log log n).
Number Theory
Divisibility, primes and modular arithmetic — the math toolkit behind cryptography.
Number-theory algorithms compute with divisibility structure: GCD via Euclid’s rule gcd(a, b) = gcd(b, a mod b) (O(log min(a, b)) steps, with gcd(a, 0) = a), LCM from a / gcd(a, b) · b, primes via sieving (Eratosthenes marks composites in O(n log log n)), and modular exponentiation by repeated squaring (O(log e) multiplications). Extended Euclid additionally returns Bézout coefficients, which is how modular inverses are computed. These primitives combine into primality tests (Fermat, Miller–Rabin), totients and modular combinatorics.
The general recipe
- Reduce the question to divisibility or modular structure (gcd, residues, prime factors).
- Pick the primitive: Euclid for gcd, sieve for many primes, fast pow for huge exponents, extended Euclid for inverses.
- Guard the arithmetic: take mods early and use widening multiplication (a·b can overflow before the mod).
- Respect preconditions: Fermat easing requires prime modulus; totient formulas need the factorization.
- Verify with brute force on small inputs before trusting the fast version.
Vocabulary you'll meet everywhere here
- Euclidean algorithm
- gcd(a, b) = gcd(b, a mod b) — logarithmic steps, the oldest algorithm still in use
- Sieve of Eratosthenes
- mark multiples of each prime; survivors are prime, O(n log log n)
- Modular exponentiation
- square-and-multiply computing aᵉ mod m in O(log e)
- Euler’s totient φ(n)
- count of integers in [1, n] coprime to n, computed from prime factorization
- Miller–Rabin
- probabilistic primality test from repeated Fermat-style checks
Where this family shows up
- Cryptography: RSA key generation and encryption are modular exponentiation and inverse computation
- Competitive programming: combinatorics under a prime modulus (nCr via factorials and inverses)
- Fraction simplification, cyclic scheduling, hash design, and any “reduce mod m” arithmetic
Common pitfalls
- Overflow before the mod: (a · b) % m overflows even when a, b fit — use 64/128-bit intermediates
- gcd(0, 0) is conventionally 0; divide-by-gcd code must special-case it
- Fermat’s little theorem only eases computation when the modulus is prime and coprime to the base
- Sieving to n but querying primes above √n for factorization — factor checks only need primes up to √x
def gcd(a, b):
while b:
a, b = b, a % b
return aRecommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.