Java 为什么';t它终止-大整数素数测试
我写了两个方法来测试一个大整数是否是素数。我从(2^64)+1开始,然后我总是加2,直到找到一个素数。以下是两种方法:Java 为什么';t它终止-大整数素数测试,java,primes,biginteger,Java,Primes,Biginteger,我写了两个方法来测试一个大整数是否是素数。我从(2^64)+1开始,然后我总是加2,直到找到一个素数。以下是两种方法: public static boolean isPrime(BigInteger n) { BigInteger max_long = BigInteger.valueOf(Long.MAX_VALUE); if (n.compareTo(max_long)<=0) return isPrime(n.longValue()); f
public static boolean isPrime(BigInteger n) {
BigInteger max_long = BigInteger.valueOf(Long.MAX_VALUE);
if (n.compareTo(max_long)<=0) return isPrime(n.longValue());
final BigInteger two = new BigInteger ("2");
if ((n.mod(two)).compareTo(BigInteger.ZERO)==0) return false;
else {
for (BigInteger i=new BigInteger ("3"); i.multiply(i).compareTo(n)<=0; i=i.add(two)) {
if((n.mod(i)).compareTo(BigInteger.ZERO)==0) return false;
}
}
return true;
}
public静态布尔值isPrime(biginger n){
biginger max\u long=biginger.valueOf(long.max\u VALUE);
如果(n.compareTo(max_long)两个for
循环每次通过循环时都需要一个BigInteger
乘法:i.multiply(i).compareTo(n)你调试过吗?应该很容易找出调试程序/打印程序在哪里卡住了。第二个版本不一定更快。这完全取决于nextProbablePrime()函数在内部的功能。它确实非常简单。My(非Java)BigInteger使用一种类似于Newton Raphson的简单算法来寻找任何N次方根,它工作得很好。而预先计算平方根确实会使事情变得更快,尽管可能没有预期的那么快。
public static boolean isPrimeImproved (BigInteger n) {
BigInteger max_long = BigInteger.valueOf(Long.MAX_VALUE);
if(n.compareTo(max_long)<=0) return isPrime(n.longValue());
final BigInteger two = new BigInteger("2");
if(n.mod(two).compareTo(BigInteger.ZERO)==0) return false;
else {
for(BigInteger i=new BigInteger("3"); i.multiply(i).compareTo(n)<=0; i=i.nextProbablePrime()) {
if(n.mod(i).compareTo(BigInteger.ZERO)==0) return false;
}
}
return true;
}