write a java program to check prime number
Answers
{
public static void main (int n)
{
int c=0;
for(int f=1;f<=n;f++)
{
if(n%f==0)
c++;
}
if(c==2)
System. out. println(''Prime number'') ;
else
System. out. println(''Not a prime number'') ;
}
}
CODE :
import java.util.*;
class prime
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number to check whether the given number is prime number or not ");
int n = sc.nextInt();
int c = 0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==2)
{
System.out.println("The entered number is a prime number");
}
else
{
System.out.println("The entered number is not a prime number");
}
}
}
Explanation:
A prime number has 2 factors .
Hence we run a for-loop and an if else statement to see the number of factors.
Then we can print the statements as necessary.