Program to Check if a Number is Prime in Java
Checking Prime Number
A prime number is a natural number greater than 1 that has no divisors other than 1 and itself.
We will explore different methods to check if a number is prime using Java programming.
Method 1: Using a for Loop
We iterate from 2 to the square root of the number and check for divisibility.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
boolean isPrime = true;
if (num < 2) {
isPrime = false;
} else {
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
System.out.println(num + " is a prime number");
else
System.out.println(num + " is not a prime number");
scanner.close();
}
}
Output:
Enter a number: 7 7 is a prime number
Method 2: Using a Function
We create a function to check for primality and return the result.
import java.util.Scanner;
public class Main {
public static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0)
return false;
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (isPrime(num))
System.out.println(num + " is a prime number");
else
System.out.println(num + " is not a prime number");
scanner.close();
}
}
Output:
Enter a number: 10 10 is not a prime number