Java Program to Check Prime or Not
To check the entered number by user is prime or not have to know about the prime number.
Prime Number :- Prime Number is divisible by 1 or itself.
So in below program we check from 2 to the half of the number
and divide it with integer i every iteration and count it division by counter c. If counter is c is then it is prime number otherwise number is not Prime.
Implementation :-
import java.util.Scanner;
class PrimeNum
{
public static void main(String[] args)
{
System.out.println("Enter a number: ");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int c=0,i;
for(i=2; i<=num/2; i++)
{
if(num%i==0)
{
c++;
break;
}
}
if(c==0)
{
System.out.println(num+" is a prime number");
}
else
{
System.out.println(num+" is not a prime number");
}
}
}
Output :-
D:\AllPrograms\1232>javac PrimeNum.java
D:\AllPrograms\1232>java PrimeNum
Enter a number:
13
13 is a prime number
D:\AllPrograms\1232>java PrimeNum
Enter a number:
11
11 is a prime number
D:\AllPrograms\1232>java PrimeNum
Enter a number:
5
5 is a prime number
D:\AllPrograms\1232>java PrimeNum
Enter a number:
12
12 is not a prime number
Comments
Post a Comment