Check Prime Number
A prime number is a whole number greater than 1 whose only divisors are 1 and itself. You get a positive integer n. Return true if n is prime and false otherwise. The number 1 is not prime.
Function
- ninteger
- the positive integer to test
- Returnsboolean
- true if n is prime, false otherwise
Constraints
1 ≤ n ≤ 231 - 1
Examples
- Input
- n = 29
- Output
- true
- Explanation
- None of
2,3,4or5divides29, and6 × 6 = 36is already past29, so no divisor is left to find.29is prime.
- Input
- n = 1
- Output
- false
- Explanation
- A prime has exactly two divisors,
1and itself.1has only one divisor, so the answer isfalse.
- Input
- n = 91
- Output
- false
- Explanation
91looks prime, but7 × 13 = 91. The divisor7turns up before the search passes√91 ≈ 9.5.
+15 hidden tests on Submit
Follow-up
Every prime above 3 has the form 6k-1 or 6k+1. Can you use that to test only a third of the candidate divisors?
Hints
Open them one at a time. Each one gives away a little more.
A prime has no divisor between
2andn-1. Do you really need to test that whole range?If
ddividesn, so doesn / d, and one of the two is at most√n. You can stop onced * dpassesn.Rule out
n < 2and even numbers other than2first. Then test odd divisors from3whiled * d ≤ n, keepingd * din a 64-bit type.
Solution
The definition says to rule out every divisor from 2 to n-1, and for the largest prime input that is over two billion divisions. Divisors come in pairs that multiply to n, and the smaller one of each pair is at most √n. So you only search up to √n, about 23,000 odd candidates at most.
Try every divisor
Correct, but does not finish on the largest tests
Intuition
The definition gives you the algorithm. A number n ≥ 2 is prime when none of 2, 3, ..., n-1 divides it. Test each candidate d with n % d == 0 and return false at the first one that divides. For 91 the loop tries 2 to 6 and stops at 7.
Handle n < 2 first. For n = 1 the range of candidates is empty, so the loop would never find a divisor and would call 1 prime.
Composite numbers usually stop early, but a prime survives every test, so the loop runs to the end. For n = 2147483647, which is prime, that is about 2.1 × 10^9 divisions, far more than a few seconds allow.
Algorithm
- If
n < 2, returnfalse. - Loop
dfrom2ton-1. - If
n % d == 0, returnfalse. - After the loop, return
true.
def isPrime(n):
if n < 2:
return False
for d in range(2, n):
if n % d == 0:
return False
return TrueTrial division up to the square root
Intuition
Divisors come in pairs. If d divides n, so does n / d, and the two multiply to n. They cannot both be larger than √n, because then their product would be larger than n. So if n has any divisor besides 1 and itself, it has one that is at most √n. For 91 the pair is 7 and 13, and 7 ≤ 9.5. If nothing up to √n divides n, nothing above it does either.
Write the bound as d * d ≤ n instead of calling a square root function. It stays in whole numbers, with no rounding. The equal sign matters: 49 = 7 × 7, and its only divisor 7 sits exactly at √49.
You can also skip half the candidates. Handle 2 on its own: an even n is prime only when it is 2. After that an odd n has only odd divisors, so start at 3 and step by 2. For n = 2147483647 the loop now runs about 23,000 times instead of 2.1 × 10^9.
Algorithm
- If
n < 2, returnfalse. - If
nis even, return whethern == 2. - Start
dat3and loop whiled * d ≤ n, using a 64-bit type ford. - If
n % d == 0, returnfalse. Otherwise add2tod. - After the loop, return
true.
def isPrime(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2 # 2 is the only even prime
d = 3
while d * d <= n:
if n % d == 0:
return False
d += 2
return True
Pitfalls and edge cases
The idea fits in one line. The bugs sit at the boundaries: the smallest inputs and the last divisor.
- Returning
truefor1. It has one divisor, not two, so it is not prime. - Rejecting
2because it is even. Checkn == 2before you rule out even numbers. - Looping while
d * d < ninstead of≤. Squares of primes such as9,49and2147117569 = 46337²then pass as primes. - Overflow in
d * d. In a 32-bitint,46341 × 46341 = 2147488281does not fit and wraps to a negative number, so the test keeps passing and the loop runs far past√n. Use a 64-bit type ford, or compared ≤ n / dinstead. - Taking the bound from a floating point
sqrtand truncating it. Adoubleis exact for everynhere, but for 64-bit inputs rounding can land one below the true root and skip the one divisor that matters.d * d ≤ nhas no such risk.
Frequently asked questions4
What is the time complexity of checking if a number is prime?
Trial division up to √n takes O(√n) time and O(1) space. For n up to 2^31-1 that is at most about 46,000 divisions, or 23,000 when you skip even divisors. Testing every divisor up to n-1 is O(n), about two billion steps for the largest input.
Why do you only check divisors up to the square root of n?
Divisors come in pairs d and n / d whose product is n. If both were larger than √n, their product would be larger than n. So every pair has a member at most √n, and if no divisor shows up by then, n is prime.
Is 1 a prime number?
No. A prime has exactly two different divisors, 1 and itself, and 1 has only one. Leaving 1 out keeps every whole number's factorization into primes unique. That is why isPrime(1) returns false.
Is there a faster way to test very large numbers for primality?
For one 32-bit number, trial division to √n is fast enough. For numbers with dozens of digits, programs use the Miller-Rabin test, which checks a few modular powers instead of trying divisors. To list every prime up to a limit, the Sieve of Eratosthenes beats testing each number on its own.
Similar problems
Problems that use the same ideas. Solving two or three of them is what makes a pattern stick.
Python
def isPrime(n):
# Write code hereCase 1
Case 2
Case 3
Input
n = 29
Expected
true