2, 3, 5, 7, 11, 13, 17
.... are the prime numbers.import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = input.nextInt();
boolean isPrime = true;
if (num == 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(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.");
}
}
}
Enter a positive integer: 5
5 is a prime number.
Enter a positive integer: 9
9 is not a prime number.
Scanner
class. We then initialize a boolean variable isPrime
to true
.isPrime
to false
. Otherwise, we use a for
loop to check whether the number is divisible by any integer between 2 and the square root of the number. If it is, we set isPrime
to false
and exit the loop using break
.System.out.println()
to print a message indicating whether the number is prime or not to the console.