Prime numbers
easy 15 minA 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?
- 2
- 3
- 4
- 5
- 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
criticalrange(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.
Wrongdef 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 > 1Rightimport 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 > 1Treating 1 (or 0) as prime
criticalA 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.
Wrongdef is_prime(n): i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True # is_prime(1) == TrueRightdef is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return TrueTesting every divisor up to n
majorIf 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.
Wrongfor d in range(2, n): # O(n) if n % d == 0: return FalseRightd = 2while d * d <= n: # O(√n) if n % d == 0: return False d += 1Calling is_prime for every number in a range
majorCounting 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).
Wrongcount = sum(1 for k in range(n) if is_prime(k))Rightdef 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
majorAfter 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 [].
Wrongp = 2while p * p <= n: while n % p == 0: factors.append(p) n //= p p += 1return factors # 14 -> [2]Rightp = 2while p * p <= n: while n % p == 0: factors.append(p) n //= p p += 1if n > 1: factors.append(n) # 14 -> [2, 7]return factorsStarting the sieve's inner loop at 2p
minorCorrect 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.
Wrongfor p in range(2, n + 1): if is_p[p]: for m in range(2 * p, n + 1, p): is_p[m] = FalseRightfor 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.