A Prime number can be divided only by 1 and itself. And it must be a whole number greater than 1.




Program Code :


import java.util.Scanner;
public class PrimeNumber{
public static void main(String[] args){
Scanner scn =new Scanner(System.in);
int n,i,c,cou=2;
System.out.println("Enter a number to find prime number =");
n=scn.nextInt();
if(n>2)
{
System.out.println("2 is prime.");
System.out.println("3 is prime.");
for(i=4;i<=n;i++)
{
for(c=2;c<i;c++)
{
if(i%c==0)
break;
}
if(c==i)
{
System.out.println(i+" is prime.");
cou+=1;
}
}
System.out.println("total prime "+cou);
}
else if(n<2)
System.out.println("There is no prime");
else
System.out.println("2 is prime.\n  total prime =1" );
}
}


Output : 

Enter a number to find prime number =
20
2 is prime.
3 is prime.
5 is prime.
7 is prime.
11 is prime.
13 is prime.
17 is prime.
19 is prime.
total prime 8
 
Top