Quick revision
The short answer
Checking whether a number is prime is a math and bits problem solved by trial division up to the square root. Divisors come in pairs, d and n / d, and one of each pair is at most the square root, so after testing 2 and 3 we only try numbers of the form 6k - 1 and 6k + 1 while i <= n / i. That takes O(sqrt n) time and O(1) space.
The solution
What it costs
| Approach | Tries in the worst case | Time | Tries for 97 |
|---|---|---|---|
| Every d from 2 to n - 1 | about n | O(n) | 95 |
| Every d up to the square root | about sqrt(n) | O(sqrt n) | 8 |
| 2, then odd d up to the square root | about sqrt(n) / 2 | O(sqrt n) | 5 |
| 2, 3, then 6k - 1 and 6k + 1 | about sqrt(n) / 3 | O(sqrt n) | 4 |
What to remember
We checked whether a number is prime by trial division. Divisors come in pairs and the smaller of each pair is at most the square root, so if nothing up to the square root divides n, nothing does. After 2 and 3 only 6k - 1 and 6k + 1 need trying, and the test i <= n / i avoids overflow. That is O(sqrt n) time and O(1) space. The clue to remember is a search for a divisor: questions about the factors of n can stop at the square root.
1What it means for a number to be prime
Imagine a box of square floor tiles that you want to lay as a neat rectangle, every row the same length. With 12 tiles you have choices: 2 rows of 6, 3 rows of 4, or 4 rows of 3. With 7 tiles you have none; they only lie in one long row of 7. A number like 7, whose tiles refuse every rectangle except the single row, is called a prime number.
Let us say it with numbers. To divide exactly means to divide with nothing left over, so 3 divides 12 because 12 = 3 x 4, while 5 does not, because 12 / 5 leaves 2 over. A divisor of a number is a whole number that divides it exactly. Every number above 1 has two divisors for free, 1 and itself, the single row of tiles. A prime is a whole number above 1 with no other divisors.
We must write a method that answers true if a number is prime and false if not. The problem is smaller than it looks. We will only try some divisors and stop at the first that works; the skill is knowing which ones are worth trying.
We will keep two examples. The first is 97, which is prime, so it makes the method work hardest. The second is 49, which is not, because 49 = 7 x 7 and its tiles lie as a perfect square. In Java we test whether d divides n with the remainder operator, n % d, which gives what is left over. If n % d is 0, d divides n, so 49 % 7 is 0 while 97 % 7 is 6.
Seven rows of seven tiles. A number of tiles that can be laid as a rectangle with at least two rows is not prime.
1The 49 tiles fill 7 rows of 7, so 49 = 7 x 7 and 49 is not prime. 97 tiles can only be laid as one long row of 97.
What to assume
- What type is the number?
- A Java int, up to 2,147,483,647 and possibly negative.
- What do 0, 1 and negative numbers give?
- False, because primes are greater than 1 by definition.
- Do we need a sure answer or a likely one?
- A sure one.
- Is it one number per call?
- Yes.
A careful candidate asks a few questions first. What type is the number? A Java int, up to 2,147,483,647 and possibly negative. What do 0, 1 and negative numbers give? False, because primes are greater than 1 by definition. Do we need a sure answer or a likely one? Sure, so we divide exactly rather than use a probability test. Is it one number per call? Yes; many numbers at once is a follow-up.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a question about divisors
A beginner reading this question for the first time takes the plan straight from the definition: try every number between 1 and n and see whether any divides it. That plan is right, and we will write it shortly. What it does not tell us is how many of those tries are really needed, and that is where the interesting part lives.
So let us look for clues. The first is the word prime. Being prime is a statement about divisors, and a question about divisors is a search: we want one number that divides n, and we may stop when we find it. A search gets shorter when we can prove that the thing we want, if it exists, must lie in a small range.
The second clue is that we are given one number and nothing else. There is no array to scan, so no data structure will help. The only tool is reasoning about how a number breaks into two factors, the two numbers that multiply to give it. In the tiles, every rectangle has a short side and a long side, and the short side can never be very long.
These clues place the question in the family called math and bits, where a fact about numbers shrinks the search. The method is called trial division: we try dividing by candidates and see whether any divides exactly. The rule to carry to other problems is that divisors come in pairs, d and n / d, so a search for a divisor, a factor pair or a perfect square only needs to go as far as the square root of n.
Some ideas look similar and do not fit. A sieve, which crosses out multiples in a table, is right when we need every prime up to a limit, but a table for one number wastes memory. Bit tricks, which test single binary digits, answer questions such as whether a number is a power of two, but primes have no pattern in their binary digits.
3The honest first attempt, trying every possible divisor
The first solution anyone would write is the brute force, which follows the definition word for word. That is a good start, because it is clearly correct and gives us something to improve. We reject numbers below 2, then try every d from 2 up to n - 1. If any d gives n % d equal to 0, n is not prime. If the loop finishes, n is prime.
Let us run it by hand. For 49 we try 2, 3, 4, 5 and 6, which all leave something over, and then 7, which leaves 0, so we return false after six divisions. For 97 every try from 2 to 96 leaves something over, and only then does the loop end and return true, after 95 divisions.
Now let us count. For a prime n nothing stops the loop early, so it runs n - 2 times. When work grows in step with n we write the time as O(n), read as order n. For 97 that is 95 divisions, nothing at all. But the largest int, 2,147,483,647, is prime, and for it the loop runs over two billion times, which takes seconds. The method keeps only d, so its extra memory, called the space, is O(1), meaning constant.
So where does the time go? Once 2 fails, 97 is odd, and an odd number has no even divisor, so 4, 6, 8 and every later even number were wasted tries. Something bigger is hiding too. After trying everything up to 9, could 50 still divide 97? Then 97 / 50 would be a whole number smaller than 2, a divisor we would already have found. That idea is the heart of the solution.
4Getting to the square root rule, one observation at a time
Let us take a number with many divisors, 36, and write them in pairs whose product is 36: 1 x 36, 2 x 18, 3 x 12, 4 x 9 and 6 x 6. The first number of each pair is always 6 or less, and 6 is the square root of 36, the number that multiplied by itself gives 36. After 6 x 6 the pairs only repeat backwards, 9 x 4, 12 x 3, and so on.
Top row: the smaller divisor of each pair. Bottom row: its partner. The two rows meet at 6, the square root of 36.
1Every divisor of 36 has a partner: 1 with 36, 2 with 18, 3 with 12, 4 with 9, and 6 with itself. Each column is one pair.
2In every pair the top number is at most 6. So if we test only up to 6, we meet one member of every pair.
3The pair 6 x 6 is where the rows meet. Past the square root the pairs simply repeat in the other order, 9 x 4, 12 x 3 and so on.
Must this hold for every number? A beginner might worry that some number has both factors large, so let us try it. Suppose n = a x b and both a and b are bigger than the square root of n. Then a x b is bigger than the square root times itself, which is n, so a x b would be bigger than n, which is impossible. At least one factor of every pair is at most the square root. In tiles, the short side of a rectangle is never longer than the side of a square.
So if nothing from 2 up to the square root divides n, nothing above it can, because its partner would be a smaller divisor we already tried. For 97, whose square root is about 9.8, we try 2 to 9 instead of 2 to 96. For the largest int the loop shrinks from two billion steps to about 46,000. The time becomes O(sqrt n), read as order square root of n.
The second improvement uses the first two tries. Once 2 fails, no even number can divide n, and once 3 fails, no multiple of 3 can. Which numbers are left? Write every number as 6k + r, where k counts the complete sixes in it and r, from 0 to 5, is what is left over; 17 is 6 x 2 + 5. Numbers with r equal to 0, 2 or 4 are even, and r = 3 gives a multiple of 3, so only r = 1 and r = 5 remain. Since 6k + 5 is one less than the next multiple of six, we call these 6k - 1 and 6k + 1: 5, 7, 11, 13, 17, 19 and so on. So after 2 and 3 we start i at 5, test i and i + 2, and add 6 each time, trying a third of the numbers up to the square root.
One more detail is the mistake that catches most people who know the square root rule. The natural loop test is i * i <= n. A Java int cannot hold numbers past 2,147,483,647, and a multiplication that passes the limit wraps round to a wrong value; 46,341 x 46,341, for example, comes out as -2,147,479,015. When n is close to the largest int, i * i for the first i past the square root wraps round to a negative number like this, which is less than n, so the loop runs on when it should stop. The cure is to write i <= n / i. Dividing cannot overflow, and for whole numbers it is true exactly when i * i <= n.
5Watching the checks on 97 and then on 49
The picture plays the method on both examples. Each cell is a possible divisor from 2 to 11. The cell being tried is marked, cells that failed are marked finished, and greyed cells are never tried, because they lie above the square root or are multiples of 2 or 3. The panel shows n, i and the remainder that decides each try.
Watch how few cells are tried for 97, and notice that the loop stops not by finding anything but by i growing past the square root.
Each cell is a possible divisor. Greyed cells are never tested: they lie above the square root, or they are multiples of 2 or 3.
- n
- 97
- sqrt(97)
- about 9.8
1We are asked about n = 97. It is not below 2 and not 2 or 3, so the first two lines let it through to the real checks.
- n
- 97
- 97 % 2
- 1
2First we try 2. 97 % 2 is 1, not 0, so 2 does not divide 97, and 97 is odd. No even number can divide it now.
- n
- 97
- 97 % 3
- 1
3Next we try 3. 97 % 3 is 1, so 3 does not divide 97 either. Multiples of 3, such as 6 and 9, are now useless too.
- n
- 97
- i
- 5
- n / i
- 19
- keep going
- yes
4The loop starts with i = 5. The test i <= n / i asks whether 5 <= 97 / 5 = 19. It is true, so 5 is still below the square root.
- n
- 97
- i
- 5
- 97 % 5
- 2
5We test i itself. 97 % 5 is 2, so 5 is not a divisor. The cells 4, 6, 8 and 9 are greyed because we never test them.
- n
- 97
- i
- 5
- 97 % 7
- 6
6We test i + 2, which is 7. 97 % 7 is 6, so 7 is not a divisor either. That is the end of the first round of the loop.
- n
- 97
- i
- 11
- n / i
- 8
- keep going
- no
7i grows by 6 to 11. Is 11 <= 97 / 11 = 8? No. 11 is above the square root, so any divisor would have shown up already.
- n
- 97
- divisions
- 4
- result
- true
8The loop ends without finding a divisor, so
isPrime(97)returns true. It took four divisions: 2, 3, 5 and 7.- n
- 49
- 49 % 2
- 1
- 49 % 3
- 1
9Now n = 49. Its square root is exactly 7. 49 % 2 is 1 and 49 % 3 is 1, so neither 2 nor 3 divides it.
- n
- 49
- i
- 5
- n / i
- 9
- 49 % 5
- 4
10The loop starts at i = 5, and 5 <= 49 / 5 = 9 is true. 49 % 5 is 4, so 5 is not a divisor and we go on to i + 2.
- n
- 49
- 49 % 7
- 0
- result
- false
1149 % 7 is 0, so 7 divides 49 and the method returns false at once. 49 = 7 x 7, the square of tiles we drew at the start.
Let us read the important frames back. In the first three frames 2 and 3 both leave 1 over, which rules out every even number and every multiple of 3 at a stroke. In the fourth, the test compares 5 with 97 / 5, which is 19 in whole number division, so the loop runs, and the tries of 5 and 7 both fail.
The seventh frame is the one to understand. i is 11, and 97 / 11 is 8, so 11 <= 8 is false and the loop stops. That is because 11 x 11 = 121 is more than 97, so 11 and everything after it lie above the square root. Nothing was found below it, so nothing exists above it, and we return true after four divisions.
For 49 the start is the same, and then 49 % 7 leaves 0. Notice that 7 was tested as i + 2, not as i, which is why the loop tries both 6k - 1 and 6k + 1. We return false at once, and the 7 is the side of the square of tiles from the start.
6The complete Java program
Here is the whole program. isPrime holds the three quick checks and the loop, and main tries both examples and some edge values: 1, 2, the perfect square 25, a negative number and the largest int. Each comment shows what that line prints.
Let us read isPrime in the order it runs. The first line returns false for any n below 2, covering 0, 1 and every negative number. The second returns true for 2 and 3, and it must come before the next line, because 2 is even and 3 is a multiple of 3, and without it both would be called composite.
The third line tries 2 and 3 together. After it we know n is at least 5 with no factor 2 or 3, so every candidate left has the form 6k - 1 or 6k + 1.
Then comes the loop. i starts at 5, the first 6k - 1, and the test i <= n / i keeps it below the square root without overflow. Inside we test i and i + 2, which are 5 and 7, then 11 and 13, and so on, returning false the moment either divides n. If the loop ends without returning, nothing up to the square root divided n, so the last line returns true.
In main, 25 tests the loop condition. Its square root is exactly 5, and 5 <= 25 / 5 is true, so the loop tries 5 and finds it. With i < n / i the loop would never run and 25 would be called prime. The largest int runs about 15,000 divisions and returns true, with no overflow.
7How much it costs, and the cases at the edges
Let us count on the example first. For 97 the method made four divisions, by 2, 3, 5 and 7, against 95 for the brute force. In general the loop runs while i is at most the square root, steps by 6 and makes two divisions a round, about sqrt(n) / 3 in all. Dividing by 3 changes the count but not how it grows, so the time is O(sqrt n). For the largest int that is 15,448 divisions instead of two billion.
The method keeps only n and i, so the extra space is O(1). The table shows that each version keeps the same idea and simply tries fewer numbers.
| Approach | Tries in the worst case | Time | Tries for 97 |
|---|---|---|---|
| Every d from 2 to n - 1 | about n | O(n) | 95 |
| Every d up to the square root | about sqrt(n) | O(sqrt n) | 8 |
| 2, then odd d up to the square root | about sqrt(n) / 2 | O(sqrt n) | 5 |
| 2, 3, then 6k - 1 and 6k + 1 | about sqrt(n) / 3 | O(sqrt n) | 4 |
The code already handles every edge case. Numbers below 2 return false on the first line. 2 and 3 return true on the second, before the multiples test could reject them. Other even numbers and multiples of 3 return false on the third line. Squares of primes, such as 25 and 49, are caught because the loop test includes equality and both i and i + 2 are tried.
The largest values are safe because the loop test divides instead of multiplying, and every answer is exact. The slip a beginner most often makes is returning true for 1, so say aloud in an interview that 1 is not prime by definition.
8Follow-up questions
How would you find all the primes up to n?
Checking each number separately would cost about n times sqrt(n), so we use the sieve of Eratosthenes. We make a boolean array for 0 to n, assume every number from 2 is prime, and for each i with i * i <= n that is still marked prime, cross out its multiples from i * i upwards, since smaller multiples were crossed out by smaller primes. What stays unmarked is prime. It takes O(n log log n) time and O(n) space.
What would you do for very large numbers, such as 64-bit values?
The square root of a large 64-bit number is about three billion, too many divisions even with the 6k step. For such numbers we use the Miller-Rabin test, which checks a few bases with fast modular powers. With a known fixed set of bases it is exact for every 64-bit value, and in Java BigInteger.isProbablePrime runs such a test for numbers of any size.
Could you skip even more candidates, for example multiples of 5?
Yes. Using blocks of 30, which is 2 x 3 x 5, we test only the 8 remainders in each block that share no factor with 30, such as 1, 7, 11 and 13. That tries 8 numbers in every 30 instead of 10, a small gain for longer code, and the time is still O(sqrt n). The 6k version is the right balance for an interview.
9Conclusion
We checked whether a number is prime by trial division. Divisors come in pairs and the smaller of each pair is at most the square root, so if nothing up to the square root divides n, nothing does. After 2 and 3 only 6k - 1 and 6k + 1 need trying, and the test i <= n / i avoids overflow. That is O(sqrt n) time and O(1) space. The clue to remember is a search for a divisor: questions about the factors of n can stop at the square root.
Open with
Let me confirm the input: an int, false for anything below 2, and an exact answer. The brute force tries every divisor from 2 to n minus 1, which is O(n), two billion divisions for the largest int.
Then, if they want more
But divisors come in pairs. If n is a times b with a the smaller, a is at most the square root, because two factors above it would multiply to more than n. So I only search up to the square root.
After testing 2 and 3, any remaining prime divisor is one less or one more than a multiple of six, since the other forms divide by 2 or 3.
So I return early below 4, return false if 2 or 3 divides n, then loop i from 5 while i is at most n divided by i, testing i and i plus 2 and stepping by six. Dividing instead of multiplying avoids overflow near the largest int.
That is O of square root of n time and constant space; 97 takes four divisions, and 49 is caught when i plus 2 is 7. For many numbers I would use a sieve.
About this answer
- Last updated
- 14 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 20 times in that collection. How it is counted
- Official documentation
- java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a program that checks whether a number is prime.": https://scrivio-interview-library.netlify.app/data-structures/solutions/write-a-program-that-checks-whether-a-number-is-prime-a612e1/