BigInteger Modulo '%' Operation & Less Than / More Than Operations

旧街凉风 提交于 2019-12-11 07:57:20

问题


Hi I have an algorithm in which I need to apply operations to BigInt's.

I understand that BigInt's can be manipulated using the Maths class such as:

import java.math.*;

BigInteger a;
BigInteger b = BigInteger.ZERO;
BigInteger c = BigInteger.ONE;
BigInteger d = new BigInteger ("3");
BigInteger e = BigInteger.valueOf(5);

a.multiply(b);
a.add(b);
a.substract(b);
a.divide(b);

I need to be able to apply greater than for a while condition e.g.

while (a > 0) {

Which gives me a syntax error saying "bad operand types for binary operator '>', first type: java.math.BigInteger, second type: int.

I also need to be able to apply the modulo (%) operator to a BigInteger.

b = a % c;

Can anyone suggest a way of doing this?

If there isn't a solution then I'm just going to have to somehow manipulate my BigInteger into an unique Long using a reduce function (which is far from ideal).

Silverzx.


回答1:


To compare BigInteger, use BigInteger.compareTo.

while(a.compareTo(BigInteger.ZERO) > 0)
    //...

And for modulo (%), use BigInteger.mod.

BigInteger blah = a.mod(b);



回答2:


For comparing BigIntegers you may use compareTo, but in the special case when you compare to 0 the signum method will also do the job(and may be a bit faster). As for taking the remainder of a given division you may use the method mod(better option here) or alternatively use divideAndRemainder which returns an array with both the result of the division and the remainder.



来源:https://stackoverflow.com/questions/15161639/biginteger-modulo-operation-less-than-more-than-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!