How to check if a number is prime in Java

A prime number is a natural number greater than 1 that is divisive by 1 and itself. For example 2, 3, 5, 7, 11, 13 are all prime numbers. A composite number is a number greater than 1 that is divisible by a number other than 1 and itself.

Check if a number is prime using for loop and if condition

We can check if a number is prime using for loop. The number n is divided by 2 and is iterated using for loop starting from 2 till n/2. Then n is checked using the if statement.

In the program below the flag value is set to false. Then i is iterated from 2 till n/2 using for loop. The if condition checks if the number is divisible by any other number in this range. If it has a factor other than 1 and itself then the flag variable is set true and the given number is not prime. If the flag variable remains false then the number is a prime number.

public class Example {
  public static void main(String[] args) {
    int n = 11;
    boolean flag = false;
    for (int i = 2; i <= n / 2; ++i) {
        if (n % i == 0) {
        flag = true;
        break;
      }
    }
    if (!flag)
      System.out.println(n + " is a prime number.");
    else
      System.out.println(n + " is not a prime number.");
  }
}

The output is

11 is a prime number.

Checking if a number is prime using while loop and if condition

The number n is iterated from n till n/2 using a while loop and each number is checked using the if condition.

The boolean variable flag is set to false initially. Then i iterated using while loop starting from 2 till n/2. The if condition checks if the number is divisible by any number other than one and itself. If a factor is found then it is not prime flag variable is set true. If the flag variable is false then the given number is a prime number.

public class Example {
  public static void main(String[] args) {
    int n = 111, i = 2;
    boolean flag = false;
    while (i <= n / 2) {
      if (n % i == 0) {
        flag = true;
        break;
      }
      ++i;
    }
    if (!flag)
      System.out.println(n + " is a prime number.");
    else
      System.out.println(n + " is not a prime number.");
  }
}

The output is

111 is not a prime number.
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions