Math for interviews: primes, GCD and fast powers
The three number-theory tools that show up again and again: testing primes up to √n, the sieve of Eratosthenes, Euclid's GCD, and exponentiation by squaring.
In short
Check one number for primality by trying divisors up to √n. Find all primes up to n with the sieve in O(n log log n). gcd(a, b) = gcd(b, a mod b). And x^n takes only O(log n) multiplications by squaring.
Primes: the sieve of Eratosthenes
To test one number, try divisors from 2 up to √n (if n has a factor bigger than √n, it also has one smaller): O(√n). To list or count all primes up to n, don't test each one: assume everything is prime and cross out the multiples of each prime.
1def primes_up_to(n):2 is_prime = [True] * (n + 1)3 is_prime[0] = is_prime[1] = False4 p = 25 while p * p <= n:6 if is_prime[p]:7 for m in range(p * p, n + 1, p):8 is_prime[m] = False9 p += 110 return [i for i in range(n + 1) if is_prime[i]]
Variables
- Start crossing at p²: smaller multiples were already crossed by smaller primes.
- You only need primes p with p² ≤ n.
- Total work: n/2 + n/3 + n/5 + … ≈ n log log n, almost linear.
GCD: Euclid's algorithm
def gcd(a, b):
while b:
a, b = b, a % b
return a
# lcm(a, b) = a // gcd(a, b) * bThe remainder shrinks fast (at least by half every two steps), so it runs in O(log min(a, b)). It's the building block for reducing fractions, lcm, and "can you measure exactly k litres with jugs of size a and b" (answer: if k is a multiple of gcd).
Fast power and big answers
Computing x^n by multiplying n times is O(n); with exponentiation by squaring it's O(log n): x^n = (x^(n/2))² when n is even, and x · x^(n−1) when odd.
def power(x, n, mod=None):
result = 1
while n:
if n & 1:
result = result * x % mod if mod else result * x
x = x * x % mod if mod else x * x
n >>= 1
return resultKey takeaways
- 01Primality of one number: trial division up to √n.
- 02All primes up to n: sieve, starting each crossing at p², O(n log log n).
- 03gcd(a, b) = gcd(b, a mod b), O(log n); lcm = a / gcd × b.
- 04Fast power: square the base, halve the exponent, O(log n).
Check your understanding
1 of 3
To test if n is prime by trial division, up to which divisor do you need to try?
Related topics
Bit manipulation
Numbers are bits, and &, |, ^, <<, >> work on them directly in O(1). Two identities solve many problems: a ^ a = 0 and a ^ 0 = a. The classic: XOR everything and the pairs cancel, leaving the single one.
8 min read →Search on the answer
If you can write a check `works(x)` that is false, false, … then true, true, … as x grows, binary search over x for the first true. Cost: O(log of the range × cost of one check).
9 min read →