问题
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