Check if an integer is Prime - Java java.lang

Java examples for java.lang:int prime

Description

Check if an integer is Prime

Demo Code


//package com.java2s;

public class Main {
    /**//  w  w  w  . j  av  a  2s  .c  om
     * Check if an integer is Prime
     * @param input number to check
     * @return True if number is prime
     * @post Number is prime if returned true
     */
    public static boolean isPrime(int input) {
        return isPrime((long) input);
    }

    /**
     * check if a long is Prime
     * @param input input number to check
     * @return True if number is prime
     * @post Number is prime if returned true
     */
    public static boolean isPrime(long input) {
        if (input < 2) {
            return false;
        }
        // no number y above sqrtx can divide x (except x))
        long maxLimit = (long) Math.sqrt(input) + 1;
        for (int i = 2; i < maxLimit; i++) {
            if (input % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Related Tutorials