How to check a number is a prime number or not in java.

Solution:- A prime no can not be divided by any other number it is divided by itself. if another no divide this prime no then is given result x.123 etc. And if a number is a divide by any other no give the result 0 then the number never a prime number.

Java Program:-

// prime no whose no that are divide by it self other no can not divide a prime no

class PrimeNoExample
{
public static void main(String… s)
{
int a=0;
int b;
int temp=0;
int n=11;
a=n/2;
if(n==0||n==1)
{
 // this condition check if no 0 and 1 then it is not a prime no
   System.out.println(n+" is not Prime number");
}
 else
 {
   // in the else condtion we can start loop from 2 because in if   condition we have already define 0 and 1 is not prime no
    for(int i=2;i<a;i++)
    {
    if(n%i==0)
    {
  // if no divided i value i mean (2,3,4……) and after divide the value is 0 then is it not a prime no 
        System.out.println(n+" is not Prime number");
        temp=1;
        break;
        }
    }
 }

if(temp==0) // this condition check if upper loop divide and no and give the result 0 then the no never a prime no and this conditon con not means the number is prime no
{
System.out.println(n+" is Prime number");
}
}
}

Copy this above code and paste a notepad file and save it “PrimeNoExample.java” file then compile and run.

Output:- 11 is Prime number.
java prime no check

Leave a Reply

Your email address will not be published. Required fields are marked *