Algorithms Playbook
ConceptTime O(n log log n) · Space O(n)8 min read

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.

Sieve of Eratosthenes: cross out the multiples
Speed
02132435465768798109111012111312141315141615171618171918201921202221232224232524262527262827292830everyone is a prime candidate
1def primes_up_to(n):
2 is_prime = [True] * (n + 1)
3 is_prime[0] = is_prime[1] = False
4 p = 2
5 while p * p <= n:
6 if is_prime[p]:
7 for m in range(p * p, n + 1, p):
8 is_prime[m] = False
9 p += 1
10 return [i for i in range(n + 1) if is_prime[i]]
Assume every number from 2 to 30 is prime, then cross out the ones that are not. 0 and 1 are not primes.

Variables

n30
Step 1/6· Crossings: 0
Starting each prime's crossing at p² is the detail interviewers look for: anything smaller was already crossed by a smaller prime.
  • 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) * b

The 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 result

Key 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