Java program to check entered number is prime or not

Prime Number

USing For Loop
import java.util.*;
class scan
{
 public static void main(String arg[])
  {
    int x,y=1,i;
	Scanner kb=new Scanner(System.in);
	System.out.println("Enter Number:-");
	x=kb.nextInt();
	
 for(i=1;i<=x/2;i++)
  {
   if(x%i==0)
    {
     y++;
    }
  }
 if(y==2)
 {
  System.out.println("Number is prime");
 }
 else
 {
   System.out.println("Number is not prime");
 }
  }
}
Using While Loop:-
import java.util.*;
class scan
{
 public static void main(String arg[])
  {
    int x,y=1,i=1;
	Scanner kb=new Scanner(System.in);
	System.out.println("Enter Number:-");
	x=kb.nextInt();
 while(i<=x/2)
  {
   if(x%i==0)
    {
     y++;
 
    }
    i++;
  }
 if(y==2)
 {
  System.out.println("Number is prime");
 }
 else
 {
   System.out.println("Number is not prime");
 }
  }
}

OUTPUT:-

prime Number

Leave a Reply

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