Check Prime Number in Java
Problem
A prime number is a number greater than 1 that has exactly two factors: 1 and itself.
Given an integer, determine whether it is a prime number.
Java Program
public class PrimeCheck {
public static void main(String[] args) {
int n = 29;
boolean isPrime = n > 1; // numbers 1 and below are never prime
// Only check divisors up to sqrt(n) — any factor beyond that has a matching smaller one
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
isPrime = false;
break; // found a divisor, no need to keep checking
}
}
System.out.println(n + " is prime: " + isPrime);
}
}Output
Core Logic
You only need to test divisors up to the square root of the number — anything larger would already have a smaller matching factor.
- 1
isPrimestarts asn > 1, since numbers ≤ 1 are never prime. - 2The loop runs
ifrom 2 upward, but only whilei * i <= n— an integer-only stand-in for checking up to√n. - 3At each
i,n % i == 0checks whetheridividesnevenly. - 4If a divisor is found,
isPrimeis set tofalseandbreakexits the loop immediately. - 5If the loop finishes with no divisor found,
nis confirmed prime.
n = 29, the loop checks i = 2 through 5 (since 6 * 6 = 36 > 29), finds no divisor, and reports 29 as prime.Key Point: Using i * i <= n instead of Math.sqrt(n) avoids floating-point comparison and keeps the bound check a cheap integer multiply.
Key Concepts
Approach 2: BigInteger.isProbablePrime()
import java.math.BigInteger;
public class PrimeCheckBigInteger {
public static void main(String[] args) {
int n = 29;
// isProbablePrime() runs a Miller-Rabin test with a certainty of 100
boolean isPrime = BigInteger.valueOf(n).isProbablePrime(100);
System.out.println(n + " is prime: " + isPrime);
}
}
Output
Core Logic
Java's BigInteger class already knows how to test primality — no need to write the divisor loop yourself.
- 1
BigInteger.valueOf(n)wraps theintinto aBigInteger. - 2
.isProbablePrime(100)runs a probabilistic primality test (Miller–Rabin) with a certainty parameter of100. - 3The certainty parameter controls the probability of a false positive — higher values make a wrong answer astronomically unlikely.
BigInteger.valueOf(29).isProbablePrime(100) returns true.Key Point: 'Probable' isn't a red flag here — with a certainty of 100, the chance of a composite number being misreported as prime is far smaller than the chance of a hardware error, and this scales to numbers far too large for a trial-division loop to check quickly.