% operator for BigInteger in java

Saendra picture Saendra · Jul 20, 2012 · Viewed 18.2k times · Source

How to use a%b with big integers? like

...
BigInteger val = new BigInteger("1254789363254125");
...

boolean odd(val){
   if(val%2!=0)
      return true;
   return false;
...

Eclipse says that operator % is undefined for BigInteger.

Any ideas?

Answer

jrad picture jrad · Jul 20, 2012

Like this:

BigInteger val = new BigInteger("1254789363254125");
public boolean odd(BigInteger val) {
    if(!val.mod(new BigInteger("2")).equals(BigInteger.ZERO))
        return true;
    return false;
}

Or as user Duncan suggested in a comment, we can take out the if statement altogether like so:

BigInteger val = new BigInteger("1254789363254125");
public boolean odd(BigInteger val) {
    return !val.mod(new BigInteger("2")).equals(BigInteger.ZERO));
}