使用大整数的方法 returns 无

Method using Big Integers returns nothing

我使用 Java 的大整数创建了费马素数测试。然而,虽然没有错误出现并且一切看起来都很好,但它不会 return 对任何输入既不真也不假(除了 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;
}

        }

这个问题是由于大整数造成的吗?

您的 a.add(BigInteger.ONE) 应该是 a = a.add(BigInteger.ONE)。否则你的 a 总是有相同的值,你的循环是无限的。

参见BigInteger#add(value)

Returns a BigInteger whose value is (this + val)

由于BigInteger,问题没有发生。该函数永远不会 returns 因为您在 for 循环中创建了无限循环:

for (BigInteger a=BigInteger.valueOf(2);a.compareTo(BigInteger.valueOf(40))<=0;a.add(BigInteger.ONE)

循环中的增量语句不会修改循环计数器。

a.add(BigInteger.ONE)

这条语句returns一个BigInteger,它不修改调用对象。