GCD (Greatest Common Divisor)
The GCD is the largest positive integer that divides both numbers without remainder.Euclid’s Algorithm - Iterative
Euclid’s Algorithm - Recursive
LCM (Least Common Multiple)
The LCM is the smallest positive integer divisible by both numbers.a / gcd(a,b) * b not a * b / gcd(a,b)
Usage:
Extended GCD
Finds integers x and y such that:a*x + b*y = gcd(a,b)
Iterative Implementation
Recursive Implementation
Mathematical Proof of Extended GCD
Mathematical Proof of Extended GCD
The Extended Euclidean Algorithm is based on the observation that:If Thus:
gcd(a,b) = g and we can express g = b*x' + (a mod b)*y', then:x = y' and y = x' - ⌊a/b⌋*y'Base case: When b = 0, we have gcd(a,0) = a = a*1 + 0*0Prime Numbers
Sieve of Eratosthenes
Efficiently finds all primes up to n.Sieve Class (Full Implementation)
Miller-Rabin Primality Test
Probabilistic test for large numbers, deterministic forn < 2^64.
Prime Factorization
As Vector (with repetitions)
As Map (prime → exponent)
Divisors
Finds all divisors of a number.Euler’s Totient Function
Counts integers from 1 to n that are coprime to n.- φ(1) = 1
- φ(p) = p - 1 for prime p
- φ(p^k) = p^k - p^(k-1) = p^(k-1)(p-1)
- φ(mn) = φ(m)φ(n) if gcd(m,n) = 1
- Σ φ(d) = n where sum is over all divisors d of n
Applications of Euler's Totient
Applications of Euler's Totient
- Euler’s Theorem: If gcd(a,n) = 1, then a^φ(n) ≡ 1 (mod n)
- Modular Inverse: a^(-1) ≡ a^(φ(n)-1) (mod n) when gcd(a,n) = 1
- Cycle Length: The multiplicative order of a modulo n divides φ(n)
- Cryptography: Used in RSA encryption