如何比较BigInteger的值作为循环中的条件? [英] How do i compare values of BigInteger to be used as a condition in a loop?
问题描述
我试图比较一个BigInteger(base)的值是否>另一个BigInteger(prime)的值,以及'a'的值是否不等于1。如果a的值不是1,它应该突破循环。我该如何比较它们?
I am trying to compare if the value of one BigInteger(base) is > the value of another BigInteger(prime) and if the value of 'a' is not equal to one. If value of a is not 1, it should break out of the loop. How should i compare them?
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;
}
}
推荐答案
你可以使用 BigInteger.compareTo(BigInteger)
。
You can compare them using BigInteger.compareTo(BigInteger)
.
在您的情况下,这将是 while(base.compareTo(prime)> 0){...}
。
In your case, this would be while (base.compareTo(prime) > 0) {...}
.
此外,您的终止条件应该是从更改为if(a!= one)
更改为 if(!a.equals(one))
,因为两个 BigInteger
具有相同整数值的变量不一定引用同一个对象(这就是 ==
和!=
test)。
Also, your termination condition should be changed from if (a != one)
to if (!a.equals(one))
since two BigInteger
variables with the same integer value are not necessarily referencing the same object (which is all that ==
and !=
test).
这篇关于如何比较BigInteger的值作为循环中的条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!