PPractick

DSA interview question

Check for Prime Number

Easy · Algorithms · Topics: basic maths, number theory

The problem

An online game hands out bonus rewards on "prime days": days when the player's streak count is a prime number. The server checks millions of streak values a day, and some are close to 10^9. Your task: decide whether N is prime, meaning greater than 1 with no divisors other than 1 and itself. Testing every number below N is hopeless at this scale; the √N trick from the divisors problem brings each check down to about 30,000 steps, and skipping even numbers halves that again.

Example: 17 → true, 25 → false (5 × 5), 1 → false.

Function signature

bool isPrime(long long n);  // true if n is prime

Test cases

Input nOutputExplanation
1false1 is not prime by definition
2trueThe only even prime
3true
4false2 × 2
17true
25false5 × 5, found when i reaches √25
97true
1000000007trueA well-known large prime
999999937trueThe largest prime below 10^9
0false

(Confirm: 0 ≤ n ≤ 10^9 or larger; numbers below 2 are not prime.)

How interviewers phrase it

Clarifying questions to ask

  1. How large can N be?
  2. How many numbers need checking? One query, or many? (Many queries up to a limit suggest a sieve.)
  3. How should 0, 1 and negative numbers be treated?

Follow-ups to expect

  1. "Why only check up to √N?"
  2. "Can you make it faster?"
  3. "What if you need all primes up to 10^7?"
  4. "What about numbers around 10^18?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in