How would you check whether a single number is prime, and if you instead needed every prime up to some limit n, would your approach change?

technical-conceptual · Junior level · software-engineering

What the interviewer is really asking

Assesses whether the candidate knows the sqrt(n) trial-division bound for testing one number, recognizes that 'all primes up to n' calls for the Sieve of Eratosthenes instead, and can compare the two by cost.

What to say

What to avoid

Example answers

Strong: For one number n, I trial-divide only up to sqrt(n): if there were a factor above the square root, its cofactor would be below it and I'd have caught that first — so testing past the root is wasted work. That's O(sqrt(n)). I'd special-case n < 2 as not prime, check 2, then only try odd divisors. For all primes up to a limit, I'd switch to the Sieve of Eratosthenes — start with everything marked prime, then for each prime p cross off multiples from p*p upward. It runs in roughly O(n log log n), which crushes calling the single-number test n times.

Weak: I'd loop from 2 up to n and check if any of them divides it evenly — if none do, it's prime.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.