How to write a java program to check the given number is prime or not?

 Prime number: It is a natural number which can be divided by 1 and itself.

Eg: 1,2,3,5,7,11,13,17,19,…

Prime number is a unique number. It has only two factors. They are 1 and the prime number.

#Java Program to check the given number is prime or not:

Logic behind the Program:

  • ·       First, we get a number as input.
  • ·       Next,set a flag setPrime as true.
  • ·       If the input is less than 1,set the flag setPrime as false.
  • ·       Else, start the process.
  • ·       Check with for loop until the the square root of the number.
  • ·       For each i value,check the number is divided by i or not. If it divided by i, then quit the loop.
  • ·       Other wise continue the loop.
  • ·       Finally,check the flag setPrime value.
  • ·       If it is true, then print the given number is prime number.
  • ·       Otherwise, print the given number is not a prime number.

 This program uses conditional statements and for loop.

public class PrimeNumber {

   public static void main(String  args[]) {

        int no = 37;

        int i;

        Boolean setPrime = true;

        if(no <= 1)

          {

            setPrime = false;

           }

         else

          {

           for (i=2;i<=Math.sqrt(no);i++)

           {

            if (no % i == 0)

            {

            setPrime = false;

            break;

           }

          }

          }

          if(setPrime)

          {

           System.out.println("Given number "+ no +" is a prime number");

          }

         else

         {

          System.out.println("Given number "+ no +" is not a prime number");

          }

    }

}

When you execute this program, you get the below output.

                               

Change the no value as 33 and check the output.


Prime numbers are useful in mathematics and cryptography. It generates the public and private keys in encryption and decryption.

No comments:

Post a Comment