# Java Program to find Prime Number

Java Program to find Prime Number : Prime Number is a positive integer number that is divisible by only two numbers, that is 1 and the number itself. Note: 1 is not a prime number as it isn’t divisible by two number.

The prime numbers are 2, 3, 5, 7, 11……. Prime Numbers

## Java Program to find Prime Number

``````public class PrimeNumber {
public static void main(String[] args) {
int n = 12;
int count = 0;
//prime number logic
for(int i = 1; i <= n; i++) {
if(n%i == 0) {
count++;
}
}
if(count == 2) {
System.out.println(n + " is a prime number");
} else {
System.out.println(n + " is not a prime number");
}
}
}``````

Here the ‘count‘ should be exactly 2, for a prime number.  In above example 12  is taken. The number is divided by number form i =1 to i = 12

``for(int i = 1; i <= n; i++)// here  n is 12 hence  i =1 to i = 12 ``

If the number is divisible then the count++ staement executes that set its value to 1

``count = 1;``

In similar way the loop continues till n is less than or equal to n.

At last, if the number is divisible by itself and 1 then the count will be equal to 2.

``````if(count == 2) {
System.out.println(n + " is a prime number");
} else {
System.out.println(n + " is not a prime number");
}``````

From definition, for a number to be prime it must be divisible by 1 and itself. So the statment count++  must execute only twice. Once at n =1 and another n=12.

#### Output

``````for n = 12
12 is not a prime number
for n = 5
5 is a prime number``````

Here for 12, count++ execute at n = 1,2,3,4,6,12  i.e count is not equal to 2. Hence it is not prime number

for 5, count++ execute at n = 1,5  i.e count is equal to 2. Hence it is a prime number

The above code can be optimized and can be written such that the number of ‘for loop’ iteration reduces as

``````public class PrimeNumber {
public static void main(String[] args) {
int n = 12;
boolean flag = false;
//prime number logic
for(int i = 2; i <= n/2; i++) {
if(n%i == 0) {
flag = true;
break;
}
}
if(flag || n == 1) {
System.out.println(n + " is not a prime number");
} else {
System.out.println(n + " is a prime number");
}
}
}``````

Here if the given number is divisible by any other number, than 1 and itself, then the number is not prime.

Here  ‘break‘ statement and  no. of ‘for loops‘ is less. Compare the two code and you will find the difference in implementation of for loop. Both the codes are correct, but you can reduce the number of iteration with the proper implementation of logic. Though, you don’t see much different, it will matter a lot when you will be a professional.

Learn about break and continue statement in java.