Check for Prime Number
Pattern: Maths basics
Decide whether a number is prime by trying divisors only up to its square root.
The problem
You are given a whole number n from 0 up to 2,147,483,647, the 32-bit limit. Return true if n is prime, meaning it is
at least 2 and its only divisors are 1 and itself. Otherwise return false. For example, 29 is prime, while 25 is not,
because 5 × 5 = 25.
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name isPrime and the range above are this guide's own.
Think first
- Which numbers below 2 should be ruled out straight away?
- To prove 91 is not prime you only need one divisor. Which small number divides it?
- If
nhas a divisor bigger than its square root, what can you say about the matching divisor?
Hints
Brute force, and why it fails
Try every d from 2 to n - 1. For a large prime such as 2,147,483,647 that is over 2 billion divisions, several
seconds of work, and every one of them fails. If you need to check many numbers, it is far too slow.
The key insight
If n = a × b, then a and b can't both be bigger than √n. So the search for a divisor can stop at √n: about 46,341
tries for the largest 32-bit number instead of 2 billion.
Dry run
| n | 29 |
|---|
n = 29. It is at least 2, so test divisors from d = 2. We only go while d × d is at most 29, so d runs up to 5. The array lists the values d will take.
The plan
if n < 2:
return false
d = 2
while d <= n div d: # d * d <= n, written so it cannot overflow
if n mod d == 0:
return false # found a divisor
d = d + 1
return true
Complexity
- Time
O(√n)- Space
O(1)
At most about √n tries. For the 32-bit limit that is roughly 46,000, which is instant.
Edge cases
- 0 and 1 return false.
- 2 returns true. The loop does not run, since
2 <= 2 / 2is false. - Squares of primes such as 25 must be caught: the loop has to include
d = 5, which is why it is<=and not<. - 2,147,483,647 (which is 2³¹ - 1) is prime. 2,147,395,600 is 46,340², so the loop must reach
d = 46,340to see it.
I've built my logic, show the code
Java
class Solution {
public boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int d = 2; d <= n / d; d++) {
if (n % d == 0) {
return false;
}
}
return true;
}
}C++
class Solution {
public:
bool isPrime(int n) {
if (n < 2) {
return false;
}
for (int d = 2; d <= n / d; d++) {
if (n % d == 0) {
return false;
}
}
return true;
}
};Python
class Solution:
def isPrime(self, n):
if n < 2:
return False
d = 2
while d <= n // d:
if n % d == 0:
return False
d += 1
return TrueCommon mistakes
- Treating 1 as prime.
- Stopping at
d < √ninstead ofd <= √n, which calls 25 or 49 prime. - Writing
d * d <= nwith 32-bit integers. Near the limitd * doverflows to a negative number and the loop goes wrong. - Using floating-point
sqrt, which can round just below a whole number and skip the last neededd.