What is the BigInteger.mod method in Java?
In Java, the
BigIntegerclass 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
modandremainderfunctions can be used to get the remainder, but themodfunction always returns a positiveBigInteger.
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
BigIntegerclass.
import java.math.BigInteger;
- In lines 5 and 6, we create two
BigIntegerobjects,val1with value-13andval2with value2.
BigInteger val1 = new BigInteger("-13");
BigInteger val2 = new BigInteger("2");
-
In line 7, we call the
modmethod on theval1object withval2as an argument. This method call will return aBigIntegerthat has a value equal to the remainder ofval1 / val2(i.e. -13 % 2 = -1).The
modfunction always returns a positive value, so the result will be1, not-1.
If you need the negative value, you can use the
remaindermethod.
BigInteger result = val1.mod(val2); //1