JAVA program to check whether a given number is prime or not
This JAVA program is to check whether a given number is a prime number or not.
For example 11 is a prime number and 8 is not a prime number.
Logic
We are using the logic of prime number which is – a prime number is divisible by 1 and number itself.
So the count should be 2.If it is greater than 2 than we know that it is also divisible by another number so it then becomes a composite number.
Dry Run of the Program
Take input as integer variable ‘n’ .Let us take n=4
1st iteration for(i=1;i<= n;i++) i.e. for(i=1;i<=3;i++)
if (n%i==0) i.e if(3%1==0) this condition is true
So c is incremented , hence c++; i.e. c=1;
2nd iteration for(i=2;i<= n;i++) i.e. for(i=2;i<=3;i++)
if (n%i==0) i.e if(3%2==0) this condition is false so c is not incremented
3rd iteration for(i=3;i<= n;i++) i.e. for(i=3;i<=3;i++)
if (n%i==0) i.e if(3%3==0) this condition is true so c is incremented
So c++; hence c=2;
For loop ends here as now when i is incremented i=4 hence i>n
Now we check the condition if(c==2)
As c=2 is true we print 3 is a prime no.
Program
import java.util.*; class prime { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the no"); int n = sc.nextInt(); int i=1,c=0; for(i=1;i<=n;i++) { if(n%i==0) { c++; } } if(c==2) { System.out.println(n+" is a PRIME no"); } else { System.out.println(n+" is a NOT a prime no"); } } }