Learning Outcome
After this lesson, you should be able to prove why a composite number must have a factor at or below square root of n.
Problem Statement
Given an integer n, return true if n is prime and false otherwise.
| Input | Output | Why |
|---|---|---|
n = 29 | true | 29 has no divisor from 2 through 5, so it is prime. |
Brute Force Approach
Try every divisor from 2 to n
- This is easy to understand but wastes many checks.
Optimized Approach
Handle small numbers first, reject multiples of 2 and 3, then test candidates of the form 6k
- 1 and 6k + 1 while i * i is at most n.
Exact Pseudocode
if n < 2:
return false
if n is 2 or 3:
return true
if n is divisible by 2 or 3:
return false
i = 5
while i * i <= n:
if n is divisible by i or i + 2:
return false
i += 6
return true
Reference Code
class Solution:
def isPrime(self, n):
if n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return TrueSample Dry Run
| Step | State | Result |
|---|---|---|
| Small checks | 29 is greater than 3 and not divisible by 2 or 3 | continue |
| i = 5 | 5
| test 5 and 7 |
| No divisor | 29 % 5 and 29 % 7 are nonzero | move ahead |
| Stop | next i is 11, and 11
| true |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(sqrt(n)) | Only possible factors up to square root of n are checked. |
| Space | O(1) | No extra data structure is used. |
Edge Cases
- n less than 2 is not prime.
- 2 and 3 are prime.
- Perfect squares like 49 must be caught, so use i * i at most n.
Interview Checklist
- Handle small values before the loop.
- Reject even numbers and multiples of 3 early.
Test 6k
- 1 and 6k + 1 candidates only.
FAQs
Why check only up to square root of n?
If both factors were larger than square root of n, their product would be larger than n.
Why use 6k plus or minus 1?
Every prime greater than 3 is beside a multiple of 6, so other candidates can be skipped.
What is the core pattern?
Square-root trial division.