API to test if a number is prime or not. - Java java.lang

Java examples for java.lang:Number

Description

API to test if a number is prime or not.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int number = 2;
        System.out.println(isPrime(number));
    }//  w w  w.j  a  va2 s  .  com

    /**
     * API to test if a number is prime or not.
     * @param number to be verified if prime or not.
     * @return true if number given as input is a prime number
     */
    public static boolean isPrime(int number) {
        boolean result = true;
        if (number == 2) {
            result = true;
        } else if (number == 1 || number % 2 == 0) //lets take 1 as non-prime
        {
            result = false;
        } else {
            int numberToCheckTill = (int) Math.sqrt(number);
            for (int i = 3; i <= numberToCheckTill; i = i + 2) {

                if ((number % i) == 0) {
                    result = false;
                    //number is not prime
                    break;
                }
            }
        }

        return result;
    }
}

Related Tutorials