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
.
public BigInteger mod(BigInteger val)
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
.
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
andremainder
functions can be used to get the remainder, but themod
function always returns a positiveBigInteger
.
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);}}
In the code above:
BigInteger
class.import java.math.BigInteger;
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