Get the prime number above n - Java java.lang

Java examples for java.lang:int prime

Description

Get the prime number above n

Demo Code


//package com.java2s;

public class Main {
    /**//from  w  w  w .  j a  va 2s  .  com
     * Get the prime number above n
     * @param n number
     * @return The next prime number after n.
     *         If n is equal to 2147483647. Returns -1, as there are no integers greater than it.
     */
    public static int getNextPrime(int n) {
        if (n == 2147483647)
            return -1;
        return (int) getNextPrime((long) n);
    }

    /**
     * Get the prime number above n
     * @param n number
     * @return The next prime number after n.
     *        If n is equal to 9223372036854775783L. Returns -1, as there are no long greater than it.
     */
    public static long getNextPrime(long n) {
        if (n < 2)
            return 2;
        if (n == 9223372036854775783L)
            return -1;
        for (long i = n + 1;; i++)
            if (isPrime(i))
                return i;
    }

    /**
     * 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