Topics › Basics › Know Basic Maths
Check for Prime Number
Java source ↗ Edit this article ↗
Jump to code:
Problem
You are given an integer n. Return true if n is prime, that is, n > 1 and the only positive divisors of n are 1 and n itself. Return false otherwise. Note that 0 and 1 are not prime, and 2 is the only even prime.
Constraints: 0 ≤ n ≤ 2^31 - 1.
Example 1
n = 29
answer = true // divisors: 1 and 29 only
Example 2
n = 25
answer = false // 25 = 5 * 5
Example 3
n = 1
answer = false // 1 has a single divisor, not two
Approach 1: Brute force, count the divisors
Intuition. Go straight from the definition: a prime has exactly two positive divisors. Count how many d in 1..n divide n and compare the count with 2. This automatically rejects 1 (one divisor) and, with the explicit n < 2 guard, 0 and negatives.
Algorithm.
- If
n < 2returnfalse. divisors = 0. Fordfrom1ton: ifn % d == 0,divisors++.- Return
divisors == 2.
static boolean bruteForce(int n) {
if (n < 2) return false;
int divisors = 0;
for (int d = 1; d <= n; d++) {
if (n % d == 0) divisors++;
}
return divisors == 2;
}
Complexity. Time O(n), one modulo per candidate. For n near 2 × 10^9 that is far too slow. Space O(1).
A slightly smarter brute force loops d from 2 to n - 1 and returns false at the first divisor. Early exit helps for composites with a small factor, but a prime still costs O(n).
Approach 2: Better, stop at the square root
Intuition. Divisors pair up: if d divides n then so does n / d, and the smaller member of each pair is at most sqrt(n). So if n has any divisor other than 1 and n, it has one in 2..sqrt(n). Test only that range; if nothing divides n there, n is prime.
The loop condition is (long) d * d <= n rather than d <= Math.sqrt(n): integer arithmetic has no rounding issues at perfect squares, and the long cast keeps d * d from overflowing for n near Integer.MAX_VALUE (where d reaches 46341 and 46341^2 exceeds 2^31).
Algorithm.
- If
n < 2returnfalse. - For
d = 2whiled * d ≤ n: ifn % d == 0returnfalse. - Return
true.
static boolean better(int n) {
if (n < 2) return false;
for (int d = 2; (long) d * d <= n; d++) {
if (n % d == 0) return false;
}
return true;
}
Dry run on n = 29: d = 2 (4 ≤ 29, 29 % 2 = 1), d = 3 (9 ≤ 29, 29 % 3 = 2), d = 4 (16 ≤ 29, 29 % 4 = 1), d = 5 (25 ≤ 29, 29 % 5 = 4), d = 6 (36 > 29, stop). No divisor found, true.
Dry run on n = 25: d = 2, d = 3, d = 4 do not divide; d = 5 (25 ≤ 25) divides, false. The <= is essential: with < the loop would stop before 5 and call 25 prime.
Complexity. Time O(sqrt(n)), at most about 46341 iterations for any int. Space O(1).
This is the answer interviewers expect for a single query. It is also the building block for divisor listing and factorisation.
Approach 3: Optimal, skip multiples of 2 and 3
Intuition. Still O(sqrt(n)), but we can test three times fewer candidates. After ruling out divisibility by 2 and 3, every remaining prime divisor is of the form 6k - 1 or 6k + 1: among any six consecutive integers 6k, 6k+1, ..., 6k+5, the ones at offsets 0, 2, 4 are even and the one at offset 3 is divisible by 3, leaving only offsets 1 and 5 (which is 6(k+1) - 1). So test 5, 7, then 11, 13, then 17, 19, and so on, stepping by 6.
Algorithm.
- If
n < 2returnfalse. Ifn < 4returntrue(that is2and3). - If
n % 2 == 0orn % 3 == 0returnfalse. - For
d = 5whiled * d ≤ n, steppingd += 6: ifn % d == 0orn % (d + 2) == 0, returnfalse. - Return
true.
static boolean optimal(int n) {
if (n < 2) return false;
if (n < 4) return true; // 2 and 3
if (n % 2 == 0 || n % 3 == 0) return false;
for (int d = 5; (long) d * d <= n; d += 6) {
if (n % d == 0 || n % (d + 2) == 0) return false;
}
return true;
}
Dry run on n = 49: not below 4, 49 % 2 = 1, 49 % 3 = 1; d = 5: 25 ≤ 49, 49 % 5 = 4, 49 % 7 = 0, return false. On n = 97: d = 5 (97 % 5 = 2, 97 % 7 = 6), d = 11 (121 > 97, stop), true.
Complexity. Time O(sqrt(n)) with roughly sqrt(n) / 3 modulo operations, so about 15000 for the largest int. Space O(1).
Is it worth it? For one query, barely. But this trial-division routine is called in a loop in problems like “count primes in a range” or “factorise every number in an array”, and a constant factor of three is real there. For truly many queries over a bounded range, precompute a sieve instead (see the related problems).
The tests check all three approaches against each other for every n up to 10000 (there are exactly 1229 primes in that range), then run the two fast versions on 10^9 + 7 (prime), 10^9 + 8 (even) and 2^31 - 1 (prime, and the input that exposes any d * d overflow).
Edge cases and pitfalls
0and1are not prime. Both must be rejected before any loop; a loop from2tosqrt(1)runs zero times and would wrongly returntruefor1.2and3. The6k ± 1version handles them with then < 4shortcut; without it,2 % 2 == 0would make2composite.- Perfect squares of primes (
4,9,25,49,121). The loop bound must bed * d <= n, not<. These are the standard off-by-one traps and all are in the tests. - Overflow in
d * d. Fornclose to2^31 - 1, computed * dinlong. Withint, the product wraps negative, the condition stays true, and the loop runs on past the square root (or, with unlucky values, forever). Math.sqrtbound.d <= (int) Math.sqrt(n)is usually correct but relies on floating point; the integer form is exact and no slower.- Negative inputs. Treated as not prime by the
n < 2guard. - Even numbers in the fast version. The
n % 2 == 0check means the loop can safely start at5and skip every even candidate; do not then also forget then % 3 == 0check, or9slips through.
Related problems
- Print all Divisors uses the identical
sqrt(n)scan but collects every divisor instead of stopping at the first. - GCD of Two Numbers is the other core
%-based routine in this step. - Count primes in range L to R is where trial division stops scaling and a sieve takes over.
- Prime factorisation of a Number and Print Prime Factors of a Number extend the same loop to extract the prime factors.