AlgoViz

Prime numbers

easy 15 min

A prime is a whole number above 1 whose only divisors are 1 and itself.

See it run

Test 37 and 91 by trial division up to the square root, sieve every prime up to 49 on a 7 by 7 grid, break 360 into a factor tree, and watch primes thin out as numbers grow.

Operations

Primality Test

Trial division: try divisors from 2 up to $\sqrt n$ and stop at the first one that divides evenly. Handle 2 on its own, then test only odd divisors.

Step 1 of 9

Is 37 prime?

  1. 2
  2. 3
  3. 4
  4. 5
  5. 6
n = 37√n = 6.08limit = 6

A prime has exactly two divisors, 1 and itself. We only need to try divisors up to \sqrt{37} \approx 6.08, so the candidates are 2 to 6. If 37 had a divisor bigger than 6, its partner 37 / d would be smaller than 6 and we would meet the partner first.

Step 1: Is 37 prime?

def is_prime(n):    if n < 2:        return False         # 0 and 1 are not prime    if n == 2:        return True          # the only even prime    if n % 2 == 0:        return False         # every other even number    i = 3    while i * i <= n:        # stop at the square root        if n % i == 0:            return False        i += 2               # odd divisors only    return Trueprint(is_prime(37))          # Trueprint(is_prime(91))          # False, 7 x 13
Time
O(√n)
Space
O(1)
testing every d up to n
O(n)
n near 10¹²
about 500,000 odd checks

Write the loop as `while i * i <= n` instead of computing a float square root. It is exact for any size of integer and avoids an off-by-one at perfect squares like 25 and 49.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Stopping just before the square root

    critical

    range(2, int(n ** 0.5)) excludes the square root itself, so perfect squares of primes like 25 and 49 are reported as prime. The bound must be inclusive.

    Wrong
    def is_prime(n):    for d in range(2, int(n ** 0.5)):   # 25: tries 2, 3, 4 only        if n % d == 0:            return False    return n > 1
    Right
    import mathdef is_prime(n):    for d in range(2, math.isqrt(n) + 1):   # includes 5 for 25        if n % d == 0:            return False    return n > 1
  • Treating 1 (or 0) as prime

    critical

    A prime needs exactly two divisors. 1 has one, so a test with no n < 2 guard returns True for 0 and 1 and breaks factorization and counting.

    Wrong
    def is_prime(n):    i = 2    while i * i <= n:        if n % i == 0:            return False        i += 1    return True          # is_prime(1) == True
    Right
    def is_prime(n):    if n < 2:        return False    i = 2    while i * i <= n:        if n % i == 0:            return False        i += 1    return True
  • Testing every divisor up to n

    major

    If n = a × b, one factor is at most √n. Looping to n - 1 does the same job in O(n) instead of O(√n): 10^12 checks instead of 10^6.

    Wrong
    for d in range(2, n):        # O(n)    if n % d == 0:        return False
    Right
    d = 2while d * d <= n:            # O(√n)    if n % d == 0:        return False    d += 1
  • Calling is_prime for every number in a range

    major

    Counting primes below 5,000,000 with trial division is O(n√n) and times out. A sieve answers the whole range in O(n log log n).

    Wrong
    count = sum(1 for k in range(n) if is_prime(k))
    Right
    def count_primes(n):    if n < 3:        return 0    is_p = [True] * n    is_p[0] = is_p[1] = False    for p in range(2, int(n ** 0.5) + 1):        if is_p[p]:            is_p[p * p::p] = [False] * len(range(p * p, n, p))    return sum(is_p)
  • Dropping the leftover prime factor

    major

    After the loop ends at √n, whatever is left above 1 is a prime larger than √n. Forget it and 14 factors as [2], 97 as [].

    Wrong
    p = 2while p * p <= n:    while n % p == 0:        factors.append(p)        n //= p    p += 1return factors           # 14 -> [2]
    Right
    p = 2while p * p <= n:    while n % p == 0:        factors.append(p)        n //= p    p += 1if n > 1:    factors.append(n)    # 14 -> [2, 7]return factors
  • Starting the sieve's inner loop at 2p

    minor

    Correct but wasteful: 2p, 3p, ..., (p-1)p were already crossed by smaller primes. Starting at p * p also lets the outer loop stop at √n.

    Wrong
    for p in range(2, n + 1):    if is_p[p]:        for m in range(2 * p, n + 1, p):            is_p[m] = False
    Right
    for p in range(2, math.isqrt(n) + 1):    if is_p[p]:        for m in range(p * p, n + 1, p):            is_p[m] = False

Interview tips

  • Pick the right tool

    • One number to test: trial division up to √n, O(√n).
    • All primes up to n, or many queries in a range: the sieve, O(n log log n).
    • Factor many numbers: sieve the smallest prime factor once, then each factorization is O(log n).
    • Numbers beyond about 10^12: Miller-Rabin instead of trial division.
  • Numbers to know cold

    • First primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.
    • 25 primes below 100, 168 below 1,000, 78,498 below a million.
    • 2 is the only even prime; 1 is not prime.
    • Every prime above 3 is 6k - 1 or 6k + 1.
  • Say it in the interview

    • "If n = a × b with both above √n, then a × b > n, so one factor is at most √n."
    • "I start crossing at p squared because smaller multiples already have a smaller prime factor."
    • "Whatever is left after dividing up to √n is itself prime."
  • Traps

    • Exclusive bounds that skip √n and call 25 prime.
    • Float square roots on huge integers; use math.isqrt or i * i <= n.
    • Count Primes usually means primes strictly less than n.