Get the prime number below n - Java java.lang

Java examples for java.lang:int prime

Description

Get the prime number below n

Demo Code


//package com.java2s;

public class Main {
    /**/* ww  w  .ja v  a 2  s  . c om*/
     * Get the prime number below n
     * @param n number
     * @return The prime number below n;
     *         If n <= 2. Returns -1, as there are no primes lower than 2. 
     */
    public static int getPrevPrime(int n) {
        return (int) getPrevPrime((long) n);
    }

    /**
     * Get the prime number below n
     * @param n number
     * @return The prime number below n
     *         If n <= 2. Returns -1, as there are no primes lower than 2. 
     */
    public static long getPrevPrime(long n) {
        if (n <= 2) {
            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