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.
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
Testing every divisor from 2 to n-1 costs over two billion divisions for the largest prime input. 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
Test each candidate d from 2 to n-1 with n % d == 0 and return false at the first one that divides. This is the definition of a prime, so it is correct once you return false for n < 2.
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.
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
If d divides n, so does n / d. Both cannot be larger than √n, or their product would be larger than n. So a composite n always has a divisor at most √n: for 91 the pair is 7 and 13, and 7 ≤ 9.5. If nothing up to √n divides n, n is prime.
Write the bound as d * d ≤ n, which stays in whole numbers with no rounding. Handle 2 on its own, since an even n is prime only when it is 2. An odd n has only odd divisors, so start at 3 and step by 2. For n = 2147483647 the loop runs about 23,000 times.
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
- 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 as9and49then pass as primes. - Overflow in
d * d. In a 32-bitint,46341 × 46341wraps to a negative number, so the loop runs far past√n. Use a 64-bit type ford, or compared ≤ n / d.
Frequently asked questions3
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.
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.
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.
def isPrime(n):
# Write code hereTest #1
Test #2
Test #3
Argument
n = 29
Expected Output
true