Java Program to Check Whether a Number is Prime or Not

prime or not in java

Java program to check whether the number is prime number or not :

Prime Number are the whole numbers which have two factors i.e. 1 and the number by itself. Some of the facts for the prime numbers are given below :-
  • 0 and 1 are not considered as prime number.
  • Except for 0 and 1, a number is either a prime number or a composite number.
  • Numbers that have more than two factors are called composite numbers.
  • The  1 is neither prime nor composite.
  • Except 2, all other even numbers are not prime.
The first 25 prime numbers (less than 100) are : 2, 3, 5, 7, 11, 13, 17, 19, 23 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.

Working :

Step 1 – Ask the user to enter a number.

Step 2 – Set  count = 0.

Step 3 – Create a loop of i from 2 to number n and increase the value of i after every iteration by 1.

Step 4 – Calculate mod(%) of n by every value of i and check whether the calculated value is equal to 0 or not.

Step 5 – If step-4 gets true then, increase the value of count by 1 and move to the step-3 until the test condition get false.

Step 6 – After getting out of the loop check the value of count is equal to 2 or not.

Step 7- If the value of count is equal to 2 then , the number is Prime, else ,number is not prime.

Step 8 – Print the result.

prime-or-not-in java

Code in Java :

import java.util.Scanner;
public class Main
{ //class declaration
public static void main(String[] args)
{ //main method declaration
Scanner sc=new Scanner(System.in); //scanner class object creation

System.out.println("Enter a number");
int n = sc.nextInt(); //taking a number n as input
int count=0;
if (n==1)
System.out.println("Not a Prime Number");
else if (n==2)
System.out.println("Prime Number");
else
{
for(int i = 2 ; i <=n ; i++)
{
if(n % i == 0) //condition for getting the factors of number n
count=count+1;
break;
}
if(count == 1) //if factors are two then, number is prime else not
System.out.println("Not a Prime Number");
else
System.out.println("Prime Number");
sc.close();
}//closing scanner class(not mandatory but good practice)
} //end of main method
}

Output :

Enter a number
12
Not a Prime Number