Check Whether a Number is Prime in Java



Given a number, let's say N, write a Java program to check whether the given number is prime or not. Prime numbers are special numbers with only two factors 1 and that number itself, they cannot be divided by any other number.

Example Scenario 1

Input: num = 1;
Output: 1 is not a prime number 

Example Scenario 2

Input: num2 = 5;
Output: 5 is a prime number 

5 is divisible by 1 and 5 only

Checking Prime Numbers using Factorization

The naive approach to check a given number is prime or not is factorization. In this process, we first divide the given number by all natural numbers less than or equal to it and then, we check the number of factors. If the count of factors is only two then, the given number is prime otherwise not.

Example

The following example is the practical illustration of above approach.

public class Example {
   public static void main(String[] args) {
      int num = 89;
      System.out.println("The given number is: " + num);
      // initial count of factors
      int count = 0;
      // to check prime number
      if(num == 2) {
         System.out.println(num + " is a prime number");
      } else {
         // checking number of factors
         for(int i = 1; i <= num; i++) {
            if(num % i == 0) {
               count++;
            }
         }
         // checking number of counts to print result
         if(count == 2) {
            System.out.println(num + " is a prime number");
         } else {
            System.out.println(num + " is not a prime number");
         }
      }
   }
}

On running, this code will show following result ?

The given number is: 89
89 is a prime number

Checking Prime Numbers using Square Root

We can optimize the above approach by checking up only to the square root of the number. The reason is that a larger factor of the number must be multiplied by a smaller one that has already been checked.

Example

The following Java program explains how to check whether a given number is prime in more optimized way.

public class Example {
   public static boolean checkPrimeFunc(int nums) {
      if (nums <= 1) {
         return false;
      }
      for (int i = 2; i <= Math.sqrt(nums); i++) {
         if (nums % i == 0) {
            return false;
         }
      }
      return true;
   }

   public static void main(String[] args) {
      int num = 29;
      System.out.println("The given number is: " + num);
      System.out.println(num + " is prime ? " + checkPrimeFunc(num));
   }
}

When you execute the above code, it will show the below result ?

The given number is: 29
29 is prime ? true
Updated on: 2024-08-01T11:55:27+05:30

24K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements