Prime number program using Java

In interviews, you may be asked to write a program for how to validate if a given number is a prime number using Java.

Validating this is very easy if you know the mathematical logic behind this. Let’s see below how we can do this. We also have the example code of Prime number program using Java.

What is a Prime Number?

Any number which can be divided either by 1 or itself only is known as a Prime number.

How to validate if a given number is a Prime number?

We will create a function where we will parse the given number as an argument. One way to check the number for it is a prime is, to check the divisibility of the given number by every number before it.

If the given number is small then the operation will be quick but what if the number is big then the arithmetic operations will be a lot. To avoid this, we make use of a mathematical theorem.

We know for a fact that, if you try division by all numbers up to the square root of the given number, and if it is found to be not divisible by any number, then it is a Prime Number.

We leverage this fact and implement it using a for loop and a method provided by Math i.e. Math.sqrt

Prime number program using Java
//Validates if a given number is Prime number
public static boolean checkPrime(int n) {
        if (n <= 1) {
            return false;
        }
        for (int i = 2; i < Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

You may also read

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.