Gets if the number passed in is prime - Java java.lang

Java examples for java.lang:Math Number

Description

Gets if the number passed in is prime

Demo Code


//package com.java2s;

public class Main {
    /**/*from   w w  w. j  a  va 2  s  .  co m*/
     * Gets if the number passed in is prime
     *
     * @param num Number to test
     * @return If the number is prime
     */
    public static boolean isPrime(long num) {
        // 0 and 1 are not prime numbers
        if (num == 0)
            return false;
        else if (num == 1)
            return false;

        // Test all possible factors of the number
        for (long i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0)
                return false;
        }

        // The number must be prime
        return true;
    }
}

Related Tutorials