Java Program to Check Prime Number


Advertisements

A Prime number is a natural number greater than $$1$$ and divisible by $$1$$ and itself only, for example $$- 2, 3, 5, 7,$$ etc.

Example: Using conditional statements

In the below example, the number called MyNum is checked for prime number by dividing it with all natural numbers starting from $$2$$ to $$N-1$$.

public class MyClass {
 public static void main(String[] args) {
    int MyNum = 17;
    int n = 0;
    for(int i = 2; i < MyNum; i++)
    {
      if(MyNum % i == 0){
        n++;
        break;
      }
    }
    if (n == 0){
      System.out.println(MyNum + " is a prime number.");
    } else {
      System.out.println(MyNum + " is not a prime number.");
    }
  }
}

Output

17 is a prime number.

Example: Using Method

In the below example, a function called primenumber() is created which takes a number as argument and checks it for prime number by dividing it with all natural numbers starting from $$2$$ to $$\frac{N}{2}$$.

public class MyClass {
 static void primenumber(int MyNum) {
    int n = 0;
    for(int i = 2; i < (MyNum/2+1); i++)
    {
      if(MyNum % i == 0){
        n++;
        break;
      }
    }
    if (n == 0){
      System.out.println(MyNum + " is a prime number.");
    } else {
      System.out.println(MyNum + " is not a prime number.");
    }
  }
 public static void main(String[] args) {
    primenumber(21);
  }
}

Output

21 is not a prime number.

Example: Optimized Code

  • Instead of checking the divisibility of given number from $$2$$ to $$\frac{N}{2}$$, it is checked till $$\sqrt{N}$$. For a factor larger than $$\sqrt{N}$$, there must the a smaller factor which is already checked in the range of $$2$$ to $$\sqrt{N}$$.
  • Except from $$2$$ and $$3$$, every prime number can be represented into $$6k\pm1$$.

public class MyClass {
 static void primenumber(int MyNum) {
    int n = 0;
    if (MyNum == 2 || MyNum == 3){
      System.out.println(MyNum + " is a prime number.");
    } else if (MyNum % 6 == 1 || MyNum % 6 == 5) {
        for(int i = 2; i*i <= MyNum; i++)
        {
          if(MyNum % i == 0){
            n++;
            break;
          }
        }
        if (n == 0){
          System.out.println(MyNum + " is a prime number.");
        } else {
          System.out.println(MyNum + " is not a prime number.");
        }
    } else {
      System.out.println(MyNum + " is not a prime number.");
    }
  }
 public static void main(String[] args) {
    primenumber(21);
  }
}

Output

21 is not a prime number.




Advertisements