# Check whether a number is prime or not

By | October 11, 2018

This post is all about How write a java program to check whether a number is prime or not We will write a java program to whether a input number is prime or not.

As we know that a number is a prime number if it is a natural number greater than 1 and it can be divided either by 1 or by the number itself. As example- 2, 3, 5, 7, 11, 13, 17,19,23..….

When we looked into definition of prime number first thing that may come to your mind to write java program for checking prime number is to have a variable in a for loop that starts from 2 (as 1 will always divide the number) and increment it by one until it reaches the number that we have to check for being prime number or not. In every iteration of the loop divide the input number by variable, if remainder is zero at any point of time then the checked number is not a prime number.

And logic would look something like below–

But this logic can be made more efficient. if We check a number is prime or not you need to run a loop starting from 2 till number/2 to check if number has any divisor exits or not.

As example – If number is 10 then you just need to check till 5 (10/2) to see if it divides by any number or not. Same way if you have a number 25 you just need to check till 12(25/2) to see if it divides completely by any number or not. We’ll use the same concept/logic to write our java program to check for prime number.

#### Note: You should note that 0 and 1 are not prime numbers. The Number two(2) is the only even prime number because all the other even numbers can be divided by 2.

Let’s write a java program check for prime number:

Now let’s run above program to test few inputs: