A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. This article prseents three different approaches to check whether a given integer is a prime number.
Method 1: Basic Approach
The most straightforward method involves checking divisibility from 2 up to the number minus one. If any number in this range divides the input evenly, it's not prime.
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (num <= 1) {
System.out.println(num + " is not a prime number");
return;
}
boolean isPrime = true;
for (int divisor = 2; divisor < num; divisor++) {
if (num % divisor == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + " is a prime number");
} else {
System.out.println(num + " is not a prime number");
}
}
}
Method 2: Optimized Range Check
For any composite number n = a × b, at least one of the factors must be less than or equal to n/2. Therefore, we only need to check divisors up to half of the number.
import java.util.Scanner;
public class OptimizedPrimeChecker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int value = input.nextInt();
if (value <= 1) {
System.out.println(value + " is not a prime number");
return;
}
boolean result = true;
for (int factor = 2; factor <= value / 2; factor++) {
if (value % factor == 0) {
result = false;
break;
}
}
if (result) {
System.out.println(value + " is a prime number");
} else {
System.out.println(value + " is not a prime number");
}
}
}
Method 3: Square Root Optimization
The most efficient approach leverages the mathematical property that for any composite number n = a × b, atleast one factor must be less than or equal to √n. This reduces the search space significantly.
import java.util.Scanner;
public class EfficientPrimeChecker {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
int candidate = reader.nextInt();
if (candidate <= 1) {
System.out.println(candidate + " is not a prime number");
return;
}
boolean status = true;
int limit = (int) Math.sqrt(candidate);
for (int index = 2; index <= limit; index++) {
if (candidate % index == 0) {
status = false;
break;
}
}
if (status) {
System.out.println(candidate + " is a prime number");
} else {
System.out.println(candidate + " is not a prime number");
}
}
}
Sample Output
Enter a number: 57
57 is not a prime number
Enter a number: 67
67 is a prime number