Knowledge / Computer Science and Engineering / Number theory for programmers

Number theory for programmers

Computer Science and Engineering (B.E./B.Tech) · Algorithms · free study notes for exams, placements and interviews

In short

Number theory for programmers is the toolkit of integer arithmetic that algorithm problems demand: divisibility, GCD/LCM, modular arithmetic, primes, factorisation, congruences and counting with divisors. It matters because answers in competitive and interview problems are almost always asked "modulo 109+7", because cryptography (RSA, Diffie-Hellman, UPI signing, Aadhaar and GSTIN check digits) is built on it, and because an O(√n) or O(log n) number-theoretic trick usually replaces an O(n) loop that times out. It is examined in GATE CS (Discrete Mathematics and Algorithms), in university papers on Design and Analysis of Algorithms and Discrete Structures, and in placement tests at TCS NQT/CodeVita, Infosys, Amazon, Microsoft, Google, Goldman Sachs, Media.net and D. E. Shaw. The topic is small in syllabus but very high in marks-per-hour because every result is a one-line formula with a short proof.

Explained

Divisibility, GCD and LCM

Modular arithmetic and fast exponentiation

Inverses, Fermat, Euler and orders

Primes: sieves, primality testing and factorisation

Divisors, factorials and binomial coefficients modulo p

Congruence systems, Diophantine equations and discrete logarithm

Multiplicative functions, Möbius and applied number theory

Key points

Formulas and examples

a = bq + r, 0 ≤ r < b (division algorithm; a, b, q, r integers, b > 0)
gcd(a, b) = gcd(b, a mod b); gcd(a, 0) = a
a·x + b·y = gcd(a, b) (Bézout; x, y from extended Euclid)
lcm(a, b) = a·b / gcd(a, b)
an mod m by binary exponentiation: an = (an/2)² if n even, a·an−1 if n odd
ap−1 ≡ 1 (mod p); a−1 ≡ ap−2 (mod p) [p prime, p ∤ a]
φ(n) = n·Π_{p|n} (1 − 1/p); aφ(n) ≡ 1 (mod n) for gcd(a, n) = 1
d(n) = Π (aᵢ + 1); σ(n) = Π (pᵢaᵢ+1 − 1)/(pᵢ − 1) [n = Π pᵢaᵢ]
v_p(n!) = Σ_{i≥1} floor(n / pi) (Legendre)
C(n, r) mod p = n! · (r!)−1 · ((n−r)!)−1 mod p
x = Σ aᵢ·Mᵢ·(Mᵢ−1 mod mᵢ) mod M, M = Πmᵢ, Mᵢ = M/mᵢ (CRT)
Σ_{i=1}^{n} floor(n/i) = total number of divisors of 1…n
Number of coprime pairs (i, j), 1 ≤ i, j ≤ n = Σ_{d=1}^{n} μ(d)·floor(n/d)²

Example 1 - extended Euclid, inverse and a Diophantine equation (a = 240, b = 46).

Example 2 - modular exponentiation and inverse.

Example 3 - totient and divisors of 360 = 2³·3²·5.

Example 4 - CRT and nCr mod p.

Example 5 - Legendre, inclusion-exclusion and a real check digit.

TaskNaiveEfficientComplexity
GCDsubtract repeatedlyEuclidO(log min(a,b))
an mod mn multiplicationsbinary exponentiationO(log n)
Primality of ndivide by all < ntrial division to √n / Miller-RabinO(√n) / O(k log³n)
Primes ≤ ntest eachEratosthenes / linear sieveO(n log log n) / O(n)
Factorise ntrial divisionPollard's rho + Miller-RabinO(n1/4)
Many C(n,r) mod pPascal tablefactorial + inverse factorialO(n) then O(1)
Inverse mod mbrute force 1…mextended Euclid / ap−2O(log m)
long long modpow(long long a, long long n, long long m){
    long long r = 1; a %= m;
    while(n > 0){ if(n & 1) r = r * a % m; a = a * a % m; n >>= 1; }
    return r;                       // a,m < 1e9 keeps products < 1e18
}
long long gcd(long long a,long long b){ return b ? gcd(b, a % b) : a; }
// sieve + smallest prime factor
vector<int> spf(N+1);
for(int i=2;i<=N;i++) if(!spf[i]) for(long long j=i;j<=N;j+=i) if(!spf[j]) spf[j]=i;

Where it is used

Interview questions

Common mistakes

Related topics

Bit manipulation · Divide and conquer · String matching: KMP, Rabin-Karp and Z · Time and space complexity · Discrete mathematics: groups and congruences · Cryptography and network security.

Open in the Knowledge reader →Find jobs →