What is the BigInteger.mod method in Java?

In Java, the BigInteger class handles big integer mathematical operations that are outside the limits of all primitive types.

The mod method of the BigInteger class can be used to find the remainder(modulo) of the division of the current BigInteger object by the passed BigInteger.

Syntax

public BigInteger mod(BigInteger val)

Parameters

This method takes a BigInteger object as an argument. This method throws ArithmeticException if the value of the argument is less than or equal to 0.

Return value

This method returns a BigInteger object. The value of the returned BigInteger object is the remainder of the division of the current BigInteger value by the passed argument value.

The return value will be a positive BigInteger.

Both the mod and remainder functions can be used to get the remainder, but the mod function always returns a positive BigInteger.

Code

The example below demonstrates how to use the mod method.

import java.math.BigInteger;
class BigIntegerModExample {
public static void main( String args[] ) {
BigInteger val1 = new BigInteger("-13");
BigInteger val2 = new BigInteger("2");
BigInteger result = val1.mod(val2);
System.out.println(result);
}
}

Explanation

In the code above:

  • In line 1, we import the BigInteger class.
import java.math.BigInteger;
  • In lines 5 and 6, we create two BigInteger objects, val1 with value -13 and val2 with value 2.
BigInteger val1 = new BigInteger("-13");
BigInteger val2 = new BigInteger("2");
  • In line 7, we call the mod method on the val1 object with val2 as an argument. This method call will return a BigInteger that has a value equal to the remainder of val1 / val2 (i.e. -13 % 2 = -1).

    The mod function always returns a positive value, so the result will be 1, not -1.

If you need the negative value, you can use the remainder method.

BigInteger result = val1.mod(val2); //1

Free Resources