4

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.

3
  • 2
    BigInteger.compareTo and BigInteger.mod.
    – Alvin Wong
    Mar 1, 2013 at 15:56
  • Great I'll have a Google now, can't see how the compareTo would work off the top of my head but .mod makes sense! Many thanks!
    – silverzx
    Mar 1, 2013 at 15:57
  • @AlvinWong you should have added that as an answer.
    – RudolphEst
    Mar 1, 2013 at 15:57

2 Answers 2

8

To compare BigInteger, use BigInteger.compareTo.

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

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

BigInteger blah = a.mod(b);
0

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.

2
  • I can't understand how the .compareTo would be used to check if a BigInt is greater than zero. Would it be like this? BigInteger n = "2712598012958912580129859"; BigInteger zero = BigInteger.ZERO; while (n.compareTo(zero) > 0) { ?
    – silverzx
    Mar 1, 2013 at 16:02
  • @silverzx exactly. Or alternatively as I suggested: while (n.signum() > 0) By the way in the solution you offer you don't need zero simply use BigInteger.ZERO in the cycle Mar 1, 2013 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.