Hello guys, today, we are going to discuss one of the most common programming exercises for beginners is, **write a program to check if a given number is prime or not?** There are many ways to check if a number is prime or not, but the most common of them is the trial division, which is what we will see in this tutorial. In my opinion, these kinds of programs are their first steps towards algorithmic understanding. You first come up with a solution, which is driven by the fact that *prime numbers *are natural numbers, that are not divisible by any positive number other than 1 and themselves. Then, you write a for loop to check every number, starting from 1 to a given number, to see if the given number is divisible by any positive number or not. This leads you to the solution.

Then you find some more the fact that there is no need to check till N-1, where N is the number we are checking for primeness, and checking till the square root of N is enough. This reduces a lot of time, especially while *checking a large number is prime or not*.

Further, you come to know that if it’s not divisible by 2, then there is no need to checking for any other even number, and you increment the counter by 2 instead of 1. So in a way, you learn how to optimize your solution by taking advantage of the facts available.

After this, you can try something like **the Fibonacci series** or maybe f**inding factorial of a number in Java** to do some more practice on programming. This will not only teach you language basics like loops, control statements like if-else, use of arithmetic, and relational operator but also helps to develop programming logic.

By the way, you can even take this problem of *checking if a number is prime or not,* to the next level, by trying to implement different algorithms for finding primes like the **sieve of Atkin** or **sieve of Eratosthenes**. In fact, in programming challenges, you often need to build your prime number cache up to a specific number to progress further in finding a solution.

## How to Find if a Given Integer Number is a Prime Number or Not?

Now, we’ll understand our Java program to see if a given integer number is prime or not. As I said, a number is called a prime number if it’s only divisible by 1 or itself, which means the prime number doesn’t have any positive divisor other than itself. There are many ways to check if the number is prime or not or generating a list of primes.

The most straightforward of them is known as **trial division**, which is a natural way of finding prime. In the trial division, you divide. It consists of testing whether n is a multiple of any integer between 2 and sqrt{n}.

In this program, I have presented three solutions or methods to check if the number is prime. The first solution is the implementation of the trial division, where we are checking from 2 to sqrt(n); we are using java.lang.Math class for calculating the square root.

Since this function returns double, we need to cast the result back into an integer. Our second method of **checking if a number is prime or not** is a little bit optimized than this as it doesn’t check division by even numbers other than two. The third method is most optimized for all three methods of prime number checking.

Btw, if you are also preparing for coding interviews or improving your algorithmic skill then I suggest you take a look at this wonderful course from Educative, **Grokking the Coding Interview: Patterns for Coding Questions**.

This is one of its kind courses that will not just teach you to solve the problem but also the pattern behind them, which means you can remember those patterns and apply them to many problems. A great way to build your coding and problem-solving skills.

## Prime Number Checker in Java

And, here is the complete Java program to check if a given number is prime or not. This question is also asked on written tests and interviews as to **how to print prime numbers from 1 to 100** or finding the prime factor of a number in Java. And, there is another exercise for you to do after this is checking if a number is Armstrong’s number or not.

importjava.util.Scanner; /** * Java Program to check if a number is Prime or Not. This program accepts a * number from command prompt and check if it is prime or not. * * @author http://java67.blogspot.com */publicclassPrimeTester{publicstaticvoidmain(String args[]) { Scanner scnr =newScanner(System.in);intnumber = Integer.MAX_VALUE; System.out.println("Enter number to check if prime or not ");while(number !=0) { number = scnr.nextInt(); System.out.printf("Does %d is prime? %s %s %s %n", number, isPrime(number), isPrimeOrNot(number), isPrimeNumber(number)); } } /* * Java method to check if an integer number is prime or not. * @return true if number is prime, else false */publicstaticbooleanisPrime(intnumber) {intsqrt = (int) Math.sqrt(number) +1;for(inti =2; i < sqrt; i++) {if(number % i ==0) { // number is perfectly divisible - no primereturnfalse; } }returntrue; } /* * Second version of isPrimeNumber method, with improvement like not * checking for division by even number, if its not divisible by 2. */publicstaticbooleanisPrimeNumber(intnumber) {if(number ==2|| number ==3) {returntrue; }if(number %2==0) {returnfalse; }intsqrt = (int) Math.sqrt(number) +1;for(inti =3; i < sqrt; i +=2) {if(number % i ==0) {returnfalse; } }returntrue; } /* * Third way to check if a number is prime or not. */publicstaticStringisPrimeOrNot(intnum) {if(num <0) {return"not valid"; }if(num ==0|| num ==1) {return"not prime"; }if(num ==2|| num ==3) {return"prime number"; }if((num * num -1) %24==0) {return"prime"; }else{return"not prime"; } } }OutputEnter number to checkifprime or not2? Does2is prime?trueprime numbertrue3? Does3is prime?trueprime numbertrue4? Does4is prime?falsenot primefalse5? Does5is prime?trueprimetrue6? Does6is prime?falsenot primefalse7? Does7is prime?trueprimetrue17? Does17is prime?trueprimetrue21? Does21is prime?falsenot primefalse131? Does131is prime?trueprimetrue139? Does139is prime?trueprimetrue

That’s all in this program about **how to check if a number is prime or not**. The number must be an integer, as the concept of prime is only for natural numbers and not for floating-point numbers. As I said, there are a couple of more algorithms for checking if a number is prime or not, and some of the algorithms are optimized for finding prime numbers.

It is imperative for every programmer to know at least one fast way of finding a prime number, as this trial division is not fast enough for real-world problems. I suggest exploring the sieve of Atkin and the sieve of Eratosthenes’s way of finding prime numbers.

Pingback: JAVA TOP 50 PROGRAMMING QUESTIONS - GRAD JOB OPENINGS