Lesson 15: Number Theory for Contests — GCD, Primes and Modular Arithmetic
Number theory is the branch of mathematics that competitive programming leans on most. A large share of contest problems is really about integers: divisibility, primes, remainders, and counting. The good news is that a small set of tools covers most of it. The first is the greatest common divisor (GCD), computed by the Euclidean algorithm — one of the oldest algorithms still in use, described by Euclid around 300 BC. The idea is simple: the GCD of a and b is the same as the GCD of b and the remainder of a divided by b, and the process stops when the remainder is zero.
The second tool is the Sieve of Eratosthenes, the standard way to find all primes up to a limit. You write down the numbers from 2 upward, cross out the multiples of 2, then the multiples of 3, then of 5, and so on; what remains are the primes. It runs in O(n log log n) time, which is nearly linear, and it is the right answer whenever a problem asks about many primes at once. If you only need to test one number, trial division up to its square root is enough — a number with no divisor up to its square root has no divisor at all.
import math
def gcd(a, b):
while b:
a, b = b, a % b
return a
def sieve(limit):
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False
for p in range(2, int(limit ** 0.5) + 1):
if is_prime[p]:
for multiple in range(p * p, limit + 1, p):
is_prime[multiple] = False
return [i for i, prime in enumerate(is_prime) if prime]
print(gcd(48, 36)) # 12
print(sieve(30)) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
print(math.gcd(48, 36)) # 12 — the standard library has it too
Modular arithmetic: keeping numbers small
Contest answers can be astronomically large — a count of paths, for example, can have hundreds of digits — so problems usually ask for the answer modulo some number, written as mod 1,000,000,007 (a prime, chosen by convention). Working modulo m means keeping only remainders after division by m: you can add, subtract and multiply remainders freely, because (a + b) mod m equals ((a mod m) + (b mod m)) mod m, and the same holds for multiplication. Division is the exception — it needs a modular inverse, which exists when the modulus is prime and the number is not a multiple of it. The practical rule is to apply the modulo after every operation, so intermediate values never grow large.
Two more number-theory tools deserve a place in your kit. Fast exponentiation (binary exponentiation) computes a^b mod m in O(log b) steps by squaring repeatedly — essential when b is huge. And the least common multiple follows from the GCD: lcm(a, b) = a * b // gcd(a, b). Together with the sieve and the Euclidean algorithm, these cover the number theory of most contests you will meet. Python also helps directly: pow(a, b, m) computes modular exponentiation in fast compiled code.
Going further
Modular arithmetic has one operation that needs care: division. There is no direct "divide the remainder" — instead you multiply by the modular inverse, a number that undoes multiplication modulo m. When the modulus is prime, Fermat's little theorem gives a practical way to find it: the inverse of a modulo a prime p is a^(p-2) mod p, which fast exponentiation computes in O(log p) steps. That is why the prime 1,000,000,007 is so convenient: inverses always exist for numbers that are not multiples of it, and division becomes just another multiplication.
Primality testing for a single large number is a different problem from sieving many small ones. Trial division up to the square root is fine for numbers up to about a trillion, but beyond that it becomes too slow, and contest problems sometimes ask about numbers far larger. The standard answer is the Miller–Rabin test, a probabilistic method that is fast and, for the number sizes used in contests, effectively certain when run with a few well-chosen bases. You do not need to implement it yet — but knowing its name means you will recognise it when a problem demands it.
The sieve is worth implementing once by hand, because the details teach the idea. Write down the numbers from 2 to 30, cross out the multiples of 2 starting from 4, then the multiples of 3 starting from 9, then the multiples of 5 starting from 25 — and notice that you can stop there, because the next prime is 7 and 7 times 7 is already past 30. What remains is the list of primes up to 30, and you found them without testing a single number for primality. That is the sieve's trick: it never asks whether a number is prime, it only marks what is not, and the unmarked numbers are the answer.
Key Terms
- GCD (greatest common divisor)
- The largest number dividing both a and b; computed by the Euclidean algorithm.
- Euclidean algorithm
- Repeatedly replacing (a, b) with (b, a mod b) until the remainder is zero; the last non-zero value is the GCD.
- Prime number
- A number greater than 1 whose only divisors are 1 and itself.
- Sieve of Eratosthenes
- An algorithm finding all primes up to a limit by crossing out multiples, in O(n log log n) time.
- Modulo (mod)
- The remainder after division; contest answers are often required mod 1,000,000,007.
- Modular arithmetic
- Arithmetic on remainders: addition, subtraction and multiplication can be done mod m at each step.
- Fast exponentiation
- Computing a^b mod m in O(log b) steps by repeated squaring.
- LCM (least common multiple)
- The smallest number divisible by both a and b; equal to a * b // gcd(a, b).
Discussion Questions
- Why does the Euclidean algorithm work? Try it by hand on gcd(1071, 462) and watch the numbers shrink.
- Why do contest problems ask for answers modulo 1,000,000,007 instead of the exact answer? What would go wrong otherwise?
- The sieve crosses out multiples of each prime starting from p × p. Why is it safe to start there instead of from 2p?
Practice Questions
- Compute gcd(1071, 462) using the Euclidean algorithm.
- Why is trial division only needed up to the square root when testing primality?
- What is 17 mod 5, and what is (17 + 8) mod 5 computed the modular way?
- Compute 2^10 mod 1000 using fast exponentiation reasoning (or pow).
- What is lcm(12, 18), and how does the GCD give it?
Show answers
- 21. 1071 = 2 × 462 + 147; 462 = 3 × 147 + 21; 147 = 7 × 21 + 0, so the last non-zero remainder is 21.
- If n has a divisor larger than its square root, the matching divisor is smaller than it. Checking up to the square root therefore finds a divisor whenever one exists.
- 17 mod 5 = 2; (17 + 8) mod 5 = (2 + 3) mod 5 = 0. You can reduce each number mod 5 first, then add, then reduce again.
- 24. 2^10 = 1024, and 1024 mod 1000 = 24; pow(2, 10, 1000) gives the same answer.
- 36, from 12 × 18 // gcd(12, 18) = 216 // 6. The GCD is 6, so the LCM is 216 / 6 = 36.