我使用Java的Big Integers创建了Fermat素数测试。但是,尽管没有错误出现并且一切看起来都很好,但是对于任何输入,它都不会返回true或false(BigInteger.valueOf(3)除外)。
public static boolean isPrime (BigInteger n){
BigInteger counter=BigInteger.ZERO;
boolean isPrime=false;
if(n.equals(BigInteger.valueOf(2)))isPrime=true;
if(n.compareTo(BigInteger.valueOf(2))>0 && n.compareTo(BigInteger.valueOf(40))<0) {
for (BigInteger a=BigInteger.valueOf(2);a.compareTo(n.subtract(BigInteger.ONE))<0;a.add(BigInteger.ONE)) {
if (a.modPow(n.subtract(BigInteger.ONE),n).equals(BigInteger.ONE)) counter.add(BigInteger.ONE);
}
if (counter.equals(n.subtract(BigInteger.valueOf(3)))) isPrime = true;
}
else {
for (BigInteger a=BigInteger.valueOf(2);a.compareTo(BigInteger.valueOf(40))<=0;a.add(BigInteger.ONE)) {
if (a.modPow(n.subtract(BigInteger.ONE),n).equals(BigInteger.ONE)) counter.add(BigInteger.ONE);
}
if (counter.equals(BigInteger.valueOf(39))) isPrime = true;
}
return isPrime;
}
}
是否由于大整数而发生此问题?
相关分类