In this Java program, you’ll learn how to Check Whether a Number is Prime or Not using the Java programming language.
Prime number– A number that is divisible only by itself and 1 is called prime number.
How to check whether a Number is Prime or Not using JAVA?
Example 1: using While loop
RUN CODE SNIPPETpublic class Main {
public static void main(String[] args) {
int num = 11, i = 2;
boolean flag = false;
while (i <= num / 2) {
if (num % i == 0) {
flag = true;
break;
}
++i;
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}OUTPUT
11 is a prime number.
In the above program, we have used while loop. The condition used here is i <= num/2 the loop will run until the condition turns out.
Example 2: using For loop
RUN CODE SNIPPETpublic class Main {
public static void main(String[] args) {
int num = 122;
boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}OUTPUT
122 is not a prime number.
In the above program, for loop is used to find out whether the given number is prime or not.
The condition used here is i <= num / 2, a prime number is not divisible by its half.
If the number is divisible then it breaks the loop and determines the number is not a prime number.
If the number is not divisible then it determines that the number is a prime number.