Saturday, January 25, 2014

How to Check if Given Number is Prime in Java - With Example

One of the most common programming exercise for beginners is, write a program to check if given number is prime or not? There are many methods to check if a number is prime or not, but most common of them is trial division, which is what we will see in this tutorial. In my opinion these kind of program are their first steps towards algorithmic understanding. You first come with a solution, which is driven by fact that prime numbers are natural numbers, which are not divisible by any positive number other than 1 and themselves. You write a for loop to check every number, starting from 1 to given number, to see if given number is divisible by any positive number or not. This leads you to the solution. Then you find some more fact that there is no need to check till N-1, where N is the number we are checking for primeness, and checking till square root of N is enough. This reduces lot of time, especially while checking a large number is prime or not. Further, you come to know that if its not divisible by 2 then there is no need to checking for any other even number, and you increment counter by 2, instead of 1. So in a way, you learn how to optimize your solution by taking advantage of facts available. After this you can try something like Fibonacci series, or may be finding factorial of a number in Java to do some more practice on programming. This will not only teach you language basics e.g. 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 next level by try to implement different algorithms for finding primes e.g. sieve of Atkin or  sieve of Eratosthenes. In fact in programming challenges, you often need to build your prime number cache up-to a certain number to progress further in finding solution. This question is also asked on written test and interview as  how to print prime numbers from 1 to 100  or finding prime factor of a number in Java.


Java Program to Check if a integer number is Prime or Not

How to check if Given number is prime in Java
This is 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 its only divisible by 1 or itself, which means prime number doesn't have any positive divisor other than itself. There are many ways to check if number is prime or not, or generating list of primes. Easiest of them is known as trial division, which is a natural way of finding prime. In 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 solution or method to check if number is prime. First solution is implementation of trial division, where we are checking from 2 to sqrt(n), we are using java.lang.Math class for calculating square root. Since this function returns double, we need to cast result back into integer. Our second method of checking if a number is prime or not is little bit optimized that this as it doesn't check division by even numbers other than two.Third method is most optimized of all three methods of prime number checking. By the way there is another exercise for you to do after this is checking if a number is  Armstrong number  or not.


import java.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
 */
public class Testing {

    public static void main(String args[]) {
        Scanner scnr = new Scanner(System.in);
        int number = 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
     */
    public static boolean isPrime(int number) {
        int sqrt = (int) Math.sqrt(number) + 1;
        for (int i = 2; i < sqrt; i++) {
            if (number % i == 0) {
                // number is perfectly divisible - no prime
                return false;
            }
        }
        return true;
    }


    /*
     * Second version of isPrimeNumber method, with improvement like not
     * checking for division by even number, if its not divisible by 2.
     */
    public static boolean isPrimeNumber(int number) {
        if (number == 2 || number == 3) {
            return true;
        }
        if (number % 2 == 0) {
            return false;
        }
        int sqrt = (int) Math.sqrt(number) + 1;
        for (int i = 3; i < sqrt; i += 2) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }


    /*
     * Third way to check if a number is prime or not.
     */
    public static String isPrimeOrNot(int num) {
        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";
        }
    }
}

Output
Enter number to check if prime or not
2? Does 2 is prime? true prime number  true
3? Does 3 is prime? true prime number  true
4? Does 4 is prime? false not prime  false
5? Does 5 is prime? true prime  true
6? Does 6 is prime? false not prime  false
7? Does 7 is prime? true prime  true
17? Does 17 is prime? true prime  true
21? Does 21 is prime? false not prime  false
131? Does 131 is prime? true prime  true
139? Does 139 is prime? true prime  true

That's all in this program about how to check if a number is prime or not. number must be integer, as concept of prime is only for natural numbers and not for floating point numbers. As I said there are couple of more algorithms for checking if a number is prime or not, and some of the algorithm is optimized for finding prime numbers. It imperative to know at-least one fast way of finding prime number,as this trial division is not fast enough for real world problems. I suggest exploring sieve of Atkin and sieve of Eratosthenes way of finding prime numbers.

3 comments:

  1. Your isPrimeOrNot() method is not a correct way to detemine if a number is prime. (num * num - 1 ) % 24 == 0 is a property that is true for all primes but it can be true for some non primes as well eg num = 25.

    Also I think the code would clearer if you didn't add one to sqrt but instead used i <= sqrt in your for() loop.

    ReplyDelete
  2. The code is not valid to check the number is prime or not, which is written in the method isPrimeOrNot(int num).
    This method will also print some non-prime number like: 25,35,49...

    ReplyDelete
    Replies
    1. You are correct the code has bug, it prints 25 has prime number.

      Delete

Java67 Headline Animator