How do i compare values of BigInteger to be used as a condition in a loop?

白昼怎懂夜的黑 提交于 2019-11-30 11:21:24

You can compare them using BigInteger.compareTo(BigInteger).

In your case, this would be while (base.compareTo(prime) > 0) {...}.

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).

Since BigIntegers are objects, you should use caution when using the equality operators. Right now, you're performing a reference comparison (which in this case, will more than likely fail). You'll need to use the equals() or compareTo() methods.

BigInteger has a built-in static variable representing one. Use the equals() method or the compareTo() method to compare values:

if (!a.equals(BigInteger.ONE)) {
    ...
}

-or-

if (a.compareTo(BigInteger.ONE) != 0) {
    ...
}

Hope that helps! See here for more information: http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html

Maybe

while (base.compareTo(prime)>0){
//rest of your loop
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!