Java Program to check if number is prime or not




Prime Numbers-  Prime number is the number which is greater than 1 and is divisible by 1 and itself only. That means , the prime number has no positive divisors other than 1 and the number itself.

Below is the program to check if entered number is prime or not.

import java.util.Scanner;

public class PrimeCheck {

       public static void main(String[] args)
      {

               int a=0;

               int n;

               System.out.println("Please enter number greater than one to check");

               Scanner sc=new Scanner(System.in);

                n=sc.nextInt();

               if(n>1)

              {

                         for(int i=2;i<=n/2;i++)

                        {

                             if(n%i==0)

                            {

                                   a=1;

                                   break;

                            }

              }

              if(a!=0)

             {

                   System.out.printf("Number %d is not prime",n);

             }

             else

             {

                   System.out.printf("Number %d is prime",n);

              }

       }

       else

       {

          System.out.println("Please enter number greater than one");

       }

   }

}

Output

Please enter number greater than one to check

1

Please enter number greater than one


Please enter number greater than one to check

2

Number 2 is prime


Please enter number greater than one to check

4

Number 4 is not prime



Explanation


  • import java.util.Scanner- This statement tells the compiler to import Scanner class to program which is contained in utils package. The Scanner class has a methods defined to accept input entered by user.
  • public class PrimeCheck- public is the access specifier defining the program can be accessed from anywhere , even outside the package. PrimeCheck  is the name of the class.
  • public static void main(String[] args) - The main() method , the starting point of any Java Program. The main() method is static means it can be called only by JVM  before any objects are created. Static methods are directly invoked by class.
  • Further , we declared the int  variable and initialized it to '0' value. Next we accepted input from user using the Scanner Class. 
  • Using if() condition , we checked to see if the user entered the number greater than 1. If not we prompt the user to enter the number greater than 1.
  • Next , using the for loop we checked if the number is prime or not. If the number is prime , we initialized the variable =1 and break out of the loop.Then using if condition , we checked value of 'a'. if it is not equal to '0' then the number is not prime , other wise  number is prime.
Java Program to check if number is prime or not Java Program to check if number is prime or not Reviewed by LanguageExpert on August 21, 2017 Rating: 5

No comments