在java中,验证超过12位的素数的有效算法是什么?

在java中,验证超过12位的素数的有效算法是什么?,java,algorithm,math,Java,Algorithm,Math,对于大小大于或等于12位的数字,如何在java中实现一个有效的代码来验证给定的数字是否为素数 示例 Input: 100123456789 Output: prime Input: 101111111111 Output: prime Input: 101740496633 Output: prime Input: 111111111111 Output:not prime Input: 157639024808 Output: not prime public static Boolean

对于大小大于或等于12位的数字,如何在java中实现一个有效的代码来验证给定的数字是否为素数

示例

Input:
100123456789
Output: prime
Input:
101111111111
Output: prime
Input:
101740496633
Output: prime
Input:
111111111111
Output:not prime
Input:
157639024808
Output: not prime
public static Boolean checkPrime(long a){
    if(a%2==0)
        return false;
    for(int i=3;i<(int)Math.sqrt(a);i=i+2){
        if(a%i==0){
            return false;
        }
    }
    return true;    
}
我尝试实现以下算法,以确定它是否为素数。但对于大于或等于12位的数字来说,这并不需要太长时间。

我的代码

Input:
100123456789
Output: prime
Input:
101111111111
Output: prime
Input:
101740496633
Output: prime
Input:
111111111111
Output:not prime
Input:
157639024808
Output: not prime
public static Boolean checkPrime(long a){
    if(a%2==0)
        return false;
    for(int i=3;i<(int)Math.sqrt(a);i=i+2){
        if(a%i==0){
            return false;
        }
    }
    return true;    
}
公共静态布尔校验素数(长a){
如果(a%2==0)
返回false;

对于(inti=3;i您可以通过只检查1/3的值而不是1/2来稍微加快速度

public static boolean checkPrime(long a) {
    if (a % 2 == 0)
        return a == 2;
    for (int i = 3; i <= (int) Math.sqrt(a); i = i + 2) {
        if (a % i == 0) {
            return false;
        }
    }
    return true;
}

public static boolean checkPrime2(long a) {
    if (a % 2 == 0 || a % 3 == 0 || a % 5 == 0) {
        return a <= 3 || a == 5;
    }
    for (int i = 6, max = (int) Math.sqrt(a); i <= max; i = i + 6) {
        if (a % (i + 1) == 0 | a % (i + 5) == 0) {
            return false;
        }
    }
    return true;
}

public static void time(String desc, BooleanSupplier run) {
    long start = System.nanoTime();
    boolean result = run.getAsBoolean();
    if (!result)
        throw new AssertionError();
    long time = System.nanoTime() - start;
    System.out.printf("%s took %.3f mill-seconds%n", desc, time / 1e6);
}

public static void main(String... args) {
    for (int i = 2; i < 1000; i++) {
        boolean a = checkPrime(i);
        boolean b = checkPrime2(i);
        if (a != b)
            throw new AssertionError(i);
    }

    for (int i = 0; i < 3; i++) {
        time("checkPrime", () -> checkPrime(9999999998987L));
        time("checkPrime2", () -> checkPrime2(9999999998987L));
    }
}

这已经开始变得足够小,以至于不清楚多个线程是否有帮助。

使用
long
而不是
int
。当参数也为
2
时,您的方法返回错误的答案。当
a
为正方形时,您的方法也可能失败。请尝试Miller-Rabin测试。只需几十行即可实现这是一种概率性测试,但对于基数a=2、3、5、7、11、13和17,只有15位及以上的数字是误报,因此对于14位及以下的基数是确定的。您可以在测试的Wiki页面上获得其他基数/大小保证re是允许所有64位数字进行确定性测试的基组合。
biginger.isProbablePrime()