How to check Prime number in java
Checking Prime number
Steps to do this:-
1.input the number from user and take a boolean number b and make it true (boolean b=true;) and take i for loop.
2. Start the loop from 2
3.check if(n%i==0) then make the boolean false and break.
4.check if b then print "this is a prime number"
else print"this is not a prime number".
The Source Code
import java.util.Scanner;
class prime
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int n,i;//n is for user input i is for loop
boolean b=true;
System.out.println("enter the number");
n=s.nextInt();
for(i=2;i<n;i++)
{
if(n%i==0)// if the number is divisable by any number b will be false
{
b=false;
break;
}
}
if(b)
{
System.out.println("this is prime number");
}
else
{
System.out.println("this is not a prime number");
}
}
class prime
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int n,i;//n is for user input i is for loop
boolean b=true;
System.out.println("enter the number");
n=s.nextInt();
for(i=2;i<n;i++)
{
if(n%i==0)// if the number is divisable by any number b will be false
{
b=false;
break;
}
}
if(b)
{
System.out.println("this is prime number");
}
else
{
System.out.println("this is not a prime number");
}
}
Comments
Post a Comment
if you like it or have any doubts please let me know