Implement isPrime method in java

In this post, we will implement isPrime method. isPrime method will take an integer as input and determine whether the number is prime or number.

A prime number is a number which has only two divisors 1 and itself. To check if the number is prime or not, we need to see if it has any other factors other than 1 or itself. If it has, then number is not prime else number is prime.

Read also: Nth prime number in java

How do we determine a range upto which we need to check if number is factor or not?

Since a number can’t be divisible by number greater than itself. We can put upper limit as n but can we do better?
Yes, we can. A number can’t have factor greater than sqrt(n), so we can decide upper limit as sqrt(n).

public static boolean isPrime(int num) {
           if (num <= 1) {
               return false;
           }
           for (int i = 2; i <= Math.sqrt(num); i++) {
               if (num % i == 0) {
                   return false;
               }
           }
           return true;
    }

We have used Math.sqrt method to find sqaure root of a number.

Java isPrime method

package org.arpit.java2blog;

public class isPrimeMain {

    public static void main(String[] args) {
        System.out.println("is 17 Prime: "+isPrime(17));
        System.out.println("is 27 Prime: "+isPrime(27));
        System.out.println("is 79 Prime: "+isPrime(79));
    }

    public static boolean isPrime(int num) {
           if (num <= 1) {
               return false;
           }
           for (int i = 2; i <= Math.sqrt(num); i++) {
               if (num % i == 0) {
                   return false;
               }
           }
           return true;
    }
}

When you run above program, you will below output

is 17 Prime: true
is 27 Prime: false
is 79 Prime: true

That’s all about Java isPrime method.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.