Jev*_*aut -1 java primes biginteger
我使用Java的Big Integers创建了一个Fermat素性测试.但是,尽管没有出现错误并且一切看起来都很好,但对于任何输入(BigInteger.valueOf(3)除外)都不会返回true或false.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这个问题是由Big Biggers引起的吗?
你的a.add(BigInteger.ONE)应该是a = a.add(BigInteger.ONE).否则你a总是有相同的值,你的循环是无限的.
返回一个BigInteger,其值为(this + val)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |