Check Whether a Number is Prime or Not in Java

Exercise:

Write a Java Program to check whether a number is prime or not.

1.Check using for loop

Click Here to View the Solution!
 public class PrimeNumber{
 
  public static void main(String[] args) {
 
    int num = 217;
    boolean flag = false;
    for (int i = 2; i <= num / 2; ++i) {
 
      // condition to check if a number is  nonprime 
      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.");
  }
} 
Click Here to View the Output!
217 is not a prime number.
Click Here to View the Explanation!
  • This program is used to find out that whether a number is prime number or not by using a for loop.
  • An integer variable num is initialized as num = 217 and a Boolean variable flag is initialized as false.
  • The for loop holds an initialization (i = 2), a condition expression (i <= num/2), and an expression that will update the value of i (++i). The reason behind initializing the value from 2 and up till num/2 in the loop is that there is no existing number which is divisible by a number that is greater than its half. Hence, the looping will occur till num/2.
  • In the body of the loop, if the value of num is divisible (non-zero remainder), then the flag will be set as true and the loop will end. And a message will be printed that num is not a prime number.
  • Else, if the value of num is divisible (zero remainder), then the flag will remain false and a message will be printed that num is a prime number.

1.Check using While loop

Click Here to View the Solution!
public class PrimeNumber {
 
  public static void main(String[] args) {
 
    int num = 29, i = 2;
    boolean flag = false;
    while (i <= num / 2) {
      // condition for nonprime number
      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.");
  }
} 
Click Here to View the Output!
29 is a prime number.
Click Here to View the Explanation!
  • This program is used to determine whether a number is a prime number or not by using a while loop.
  • Initially, two integer variables num and i are initialized as num = 29 and i = 2. And a Boolean type variable flag is also initialized as flag = false.
  • The while loop will hold the same condition as the above program (i <= num/2). Hence, the loop will continue till this condition becomes false.
  • In every iteration, num is checked that whether it is divisible by i or not and an increment is done in the variable i so as to continue the while loop till num/2.
  • Lastly, a message will be printed stating 29 is a prime number.

%d bloggers like this: