Saturday 28 May 2016

How to Check if Given Number is Prime Number in Java

Before writing a progarm to check if a number is prime or not, let's first revise what is a prime number? In Maths, a number is said to be prime if it is not divisible by any number other than itself. You can now convert this definition to code and create your Java program to check if given number is prime or not.

All you need to do is create a method like public boolean isPrimeNumber(int number). This method should accept an integer number and return a boolean value true or false depending upon whether given number is prime or not.

The logic of method should check starting from the first prime number to the number itself whether the given number is divisible by any number in between or not. You can use for loop to code this part. The loop gives you luxury to repeat an action upto how many times you want or allow you to stop execution when certain condition is met.  Let's see this solution in action.


How to find if a number is Prime in Java

Based upon the definition of "prime numbers",  here is the code which checks if given number is prime or not in Java:


 public static boolean isPrimeNumber(int number) {      
        for (int i = 2; i < number; i++) {
            if (number % i == 0) {
                return false;
            }
        }        return true;
    } 

It's simple and easy to understand, but it's not efficient because mathematically it's only required to check upto square root of a number to determine if it's prime or not. That will improve the execution time of this solution by double because square root is often less than or equal to halft of the number itself. I have used that as our preffered solution in this program, which you will see in next section.


Java Program to find if a number is Prime or Not


import java.util.Scanner;

/*
 * Write a Program to check if a number is prime or not
 * input = 5
 * output = true
 * input = 4
 * output = false;
 */
public class PrimeNumber {

    public static void main(String[] args) {

        // using Scanner to read input from command prompt
        Scanner commandPromptReader = new Scanner(System.in);

        // switch to stop the loop
        int number = 1;

        while (number != 0) {
            System.out.println("Enter a number to check prime, 
                                  Enter zero to exit ");
            number = commandPromptReader.nextInt();
            if (isPrimeNumber(number)) {
                System.out.printf("Given number %d is prime %n",
                                      number);
            } else {
                System.out.printf("Given number %d is not a 
                        prime number %n",
                        number);
            }
        }

        // closing scanner to avoid resource leak
        commandPromptReader.close();

    }

    /**
     * checks if given number is prime or not
     *     
     * @param number
     * @return true if given number is prime, false otherwise
     */
    public static boolean isPrimeNumber(int number) {
        int root = (int) Math.sqrt(number);
        for (int i = 2; i <= root; i++) {
            if (number % i == 0) {
                return false;
            }
        }

        return true;
    }

}

Output
Enter a number to check prime, Enter zero to exit
2
Given number 2 is prime
Enter a number to check prime, Enter zero to exit
3
Given number 3 is prime
Enter a number to check prime, Enter zero to exit
5
Given number 5 is prime
Enter a number to check prime, Enter zero to exit
6
Given number 6 is not a prime number
Enter a number to check prime, Enter zero to exit
17
Given number 17 is prime
Enter a number to check prime, Enter zero to exit
21
Given number 21 is not a prime number
Enter a number to check prime, Enter zero to exit
23
Given number 23 is prime
Enter a number to check prime, Enter zero to exit
31
Given number 31 is prime
Enter a number to check prime, Enter zero to exit
25
Given number 25 is not a prime number
Enter a number to check prime, Enter zero to exit

That's about it. Now, you know how to check if a given number is a prime number or not. As I said there are many sophisticated algorithm exists to find prime numbers upto a given number e.g. Sieve of Eratosthenes.

If you ever need an array of prime numbers, you should be using Sieve of Eratosthenes, instead of obtaining the maximum number and check each number upto that is prime or not. That would not be as efficient as Sieve of Eratosthenes.

This solution is purely for teaching and educational purpose, basically to teach a non-programmer to code.


No comments:

Post a Comment