A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Formally, n is prime ⇔ it cannot be written as a × b where a > 1 and b > 1.
Why this matters:
- Prime testing is foundational in number theory, cryptography (RSA keys!), hashing, random-number generators, and countless coding interview puzzles.
- Writing progressively faster primality checks trains your ability to reason about loops, divisors, and mathematical bounds.
Here’s the [Problem Link] to begin with.
Quick Examples
n | Output | Explanation |
|---|---|---|
| 2 | True | Only divisors are 1 and 2. |
| 4 | False | Divisible by 2. |
| 17 | True | No divisor other than 1 and 17 itself. |
| 1 | False | By definition, 1 is not prime. |
In the following sections we’ll build three increasingly efficient solutions.
Interactive Visualizer: Trial Division up to √n
Type any number up to 1,000,000,000 and press Next to see which divisors get tested. The bars compare how many loop iterations each of the three methods in this post needs for the same number.
Brute Force Solution
Intuition & Approach
The most straightforward idea is:
- Edge Case: 1 is not prime.
- Try every integer
ifrom 2 up ton-1. - If any
idividesnevenly (n % i == 0),nis composite; otherwise it’s prime.
Code Implementation
class Solution:
def isPrime(self, n):
if n == 1: # 1 is not prime
return False
# test every possible divisor from 2 up to n-1
for i in range(2, n):
if n % i == 0: # found a divisor → not prime
return False
return True # no divisors found → primeclass Solution {
static boolean isPrime(int n) {
if (n == 1) return false; // 1 is not prime
// test every possible divisor from 2 up to n-1
for (int i = 2; i < n; i++) {
if (n % i == 0) return false; // found a divisor → not prime
}
return true; // no divisors found → prime
}
}class Solution {
public:
bool isPrime(int n) {
if (n == 1) return false; // 1 is not prime
// test every possible divisor from 2 up to n-1
for (int i = 2; i < n; i++) {
if (n % i == 0) return false; // found a divisor → not prime
}
return true; // no divisors found → prime
}
};Code Explanation
- The
forloop exhaustively checks all potential divisors. - Early exit on the first successful division saves some time, but worst-case still touches every number below
n.
Dry Run (n = 10)
i=2→10 % 2 == 0→ returnsFalse.- Loop stops immediately.
Time & Space Complexity
- Time:
O(n)(linear inn). - Space:
O(1)– constant auxiliary memory.
Conclusion
Elegant in its simplicity, but painfully slow for large numbers (think millions or cryptographic bit-lengths).
Better Solution (Half-Range Check)
Intuition & Approach
A composite number must have at least one factor ≤ n/2.
Therefore we only need to test divisors up to ⌊n/2⌋.
Code Implementation
class Solution:
def isPrime(self, n):
if n == 1: # still not prime
return False
# any factor bigger than n//2 leaves a co-factor < 2
for i in range(2, n // 2 + 1):
if n % i == 0: # divisor found
return False
return Trueclass Solution {
static boolean isPrime(int n) {
if (n == 1) return false; // still not prime
// any factor bigger than n/2 leaves a co-factor < 2
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) return false; // divisor found
}
return true;
}
}class Solution {
public:
bool isPrime(int n) {
if (n == 1) return false; // still not prime
// any factor bigger than n/2 leaves a co-factor < 2
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) return false; // divisor found
}
return true;
}
};Code Explanation
- Reduces the divisor range roughly by half, yet retains the same early-exit behavior.
Dry Run (n = 15)
Divisor loop iterates i = 2 … 7; finds i = 3 quickly, returns False.
Time & Space Complexity
- Time:
O(n/2)→ still expressed asO(n)(constants dropped). - Space:
O(1).
Conclusion
A modest improvement; still far from efficient when n is large.
Optimal Solution (Square-Root Bound)
Intuition & Approach
If n is composite, it can be factored into a × b = n.
At least one factor a ≤ √n.
So it suffices to test divisors only up to ⌊√n⌋.
Code Implementation
class Solution:
def isPrime(self, n):
if n == 1: # handle 1
return False
# only test up to √n
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0: # divisor within √n found
return False
return True # prime if loop finishesclass Solution {
static boolean isPrime(int n) {
if (n == 1) return false; // handle 1
// only test up to √n (i * i <= n avoids floating point)
for (long i = 2; i * i <= n; i++) {
if (n % i == 0) return false; // divisor within √n found
}
return true; // prime if loop finishes
}
}class Solution {
public:
bool isPrime(int n) {
if (n == 1) return false; // handle 1
// only test up to √n (i * i <= n avoids floating point)
for (long long i = 2; i * i <= n; i++) {
if (n % i == 0) return false; // divisor within √n found
}
return true; // prime if loop finishes
}
};Code Explanation
- The loop bound
int(n ** 0.5) + 1computes the floor of √nand includes it. - Once past that limit, any remaining divisor would pair with one below the limit, which we’d have already checked.
Dry Run (n = 29)
- √29 ≈ 5.38 → test
i = 2,3,4,5. - None divide evenly → returns
True.
(Brute force would have checked up to 28.)
Time & Space Complexity
- Time:
O(√n)– a dramatic speedup, especially for big inputs. - Space:
O(1).
Conclusion
Using the square-root insight slashes runtime from linear to sub-linear, transforming primality testing into a practically instantaneous task for medium-sized integers. For industrial-strength cryptography you’d employ even faster algorithms (e.g., Miller–Rabin), but for typical interview constraints this √n approach is optimal and elegant.
Key Takeaways
- Start simple, verify correctness, then refine the bounds.
- Cutting the search space from
n→n/2→√nshows the power of mathematical reasoning. - These same bounding ideas generalize to many divisor-based and search problems.
Now you’re equipped with three tiers of prime-checking solutions, ready for anything from classroom exercises to tech-interview whiteboards!
Frequently Asked Questions
How do you check if a number is prime?
Try dividing it by every whole number from 2 up to its square root. If none of them divides it evenly, the number is prime. For example, 97 is prime because none of 2 to 9 divides it, while 91 is not prime because 91 = 7 × 13.
Why is it enough to check divisors up to √n?
If n = a × b and both a and b were bigger than √n, their product would be bigger than n. So every composite number has at least one divisor that is less than or equal to √n.
Is 1 a prime number? What about 0 and 2?
1 is not prime because a prime must have exactly two divisors, 1 and itself. 0 is not prime either. 2 is prime, and it is the only even prime number.
What is the time complexity of checking a prime number?
The square-root method runs in O(√n) time and O(1) space. The brute force method that tries every number up to n−1 is O(n), and the half-range method is O(n/2), which is still O(n).
What is the fastest way to find many prime numbers?
To test one number, trial division up to √n is enough. To find all primes up to a limit, use the Sieve of Eratosthenes, which marks multiples of each prime and runs in O(n log log n).
For any changes to the article, kindly email at co**@**********ug.in or contact us at +91-9712928220.
