A primality test - Java java.lang

Java examples for java.lang:int prime

Description

A primality test

Demo Code


//package com.java2s;

public class Main {
    /**/*from ww  w .j a  v a2s  .co  m*/
     * A primality test
     * @param n number to test
     * @return true if prime
     *     false if composite
     */
    public static boolean isPrime(int n) {
        return isPrime((long) n);
    }

    /**
     * A primality test
     * @param n number to test
     * @return true if prime
     *     false if composite
     */
    public static boolean isPrime(long n) {
        if (n == 2 || n == 3)
            return true;
        if (n % 2 == 0 || n % 3 == 0 || n < 2)
            return false;

        long sqrt = (long) Math.sqrt(n) + 1;

        for (long i = 6; i <= sqrt; i += 6) {
            if (n % (i - 1) == 0)
                return false;
            else if (n % (i + 1) == 0)
                return false;
        }
        return true;
    }
}

Related Tutorials