如何比较BigInteger的值作为循环中的条件?

Sca*_*car 17 java biginteger

我试图比较一个BigInteger(base)的值是否>另一个BigInteger(prime)的值,以及'a'的值是否不等于1.如果a的值不是1,它应该突破循环.我该如何比较它们?

 Random ran = new Random();
    BigInteger prime = new BigInteger(16,ran);
    BigInteger base,a,one;
    one = new BigInteger("1");

    for (int i = 0; i < 65535; i++){

        while (base>prime){
            base = new BigInteger(16,ran);
        }
        a = base.modPow(prime.subtract(one),prime);
        System.out.println("a: "+a);    
        if (a != one){
            break;          
        }   
    }
Run Code Online (Sandbox Code Playgroud)

Ted*_*opp 31

您可以使用它们进行比较BigInteger.compareTo(BigInteger).

在你的情况下,这将是while (base.compareTo(prime) > 0) {...}.

此外,您的终止条件应该从更改为if (a != one),if (!a.equals(one))因为BigInteger具有相同整数值的两个变量不一定引用同一个对象(这就是所有这些==并且!=测试).


pse*_*ble 7

由于BigIntegers是对象,因此在使用相等运算符时应谨慎使用.现在,您正在执行参考比较(在这种情况下,很可能会失败).您需要使用equals()compareTo()方法.

BigInteger有一个内置的静态变量代表一个.使用equals()方法或compareTo()方法比较值:

if (!a.equals(BigInteger.ONE)) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

-要么-

if (a.compareTo(BigInteger.ONE) != 0) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!有关更多信息,请参见此处:http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html

  • 看起来他需要compareTo和equals.看这里:"......如果'a'的值不等于1.如果a的值不是1,它应该突破循环." 此外,他的代码显示了他称为"一"的新BigInteger与另一个计算值"a"之间的相等性检查.对不起,过时的链接. (2认同)