get Previous Prime number - Java java.lang

Java examples for java.lang:int prime

Description

get Previous Prime number

Demo Code


//package com.java2s;

import java.util.Collection;

import static java.lang.Math.sqrt;

public class Main {
    public static long getPrevPrime(long startVal) {
        for (long i = startVal - 1;; i--)
            if (isPrime(i))
                return i;
    }/*  w  w  w.  j ava  2 s .  c o m*/

    public static boolean isPrime(long test) {
        if (test < 2)
            return false;
        if (test < 4)
            return true;
        if (test % 2 == 0)
            return false;
        if (test < 9)
            return true;
        if (test % 3 == 0)
            return false;

        long sqrt = (long) sqrt(test);
        long i = 5;
        while (i <= sqrt)
            if (test % (i) == 0 || test % (i + 2) == 0)
                return false;
            else
                i += 6;

        return true;
    }

    public static boolean isPrime(long test, Collection<Long> primes) {
        if (test < 2)
            return false;

        for (Long prime : primes) {
            if (prime * prime > test)
                return true;
            if (test % prime == 0)
                return false;
        }
        //Return false here is better than false true if collection is not big enough
        return false;
    }
}

Related Tutorials