Search code examples
javabiginteger

% operator for BigInteger


How to use a % b with big integers?

Example

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


Solution

  • 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));
    }