BigInteger mod() Method in Java

 Java provides a method called BigInteger.mod() which is used to find the remainder after dividing one BigInteger by another BigInteger. This method always returns a non-negative BigInteger.

To use the mod() method, you need to pass a BigInteger object as a parameter. For example, if you have two BigInteger objects called BigInteger1 and BigInteger2, you can find the remainder by calling the mod() method on BigInteger1 and passing BigInteger2 as the parameter.

If BigInteger2 is less than or equal to zero, the mod() method throws an ArithmeticException.

Here is an example program that uses the mod() method:

Java

import java.math.BigInteger;

public class Example { public static void main(String[] args) { BigInteger BigInteger1 = new BigInteger("321456"); BigInteger BigInteger2 = new BigInteger("31711");

sql
BigInteger result = BigInteger1.mod(BigInteger2); System.out.println("The remainder of BigInteger1 divided by BigInteger2 is: " + result); }

}

Output: The remainder of BigInteger1 divided by BigInteger2 is: 4346

In this example, we created two BigInteger objects called BigInteger1 and BigInteger2. We then called the mod() method on BigInteger1 and passed BigInteger2 as the parameter. The mod() method returned a BigInteger object that contains the remainder, which we stored in the result variable. We then printed the result variable to the console.

If both BigInteger objects have the same value, the mod() method returns 0. Here is an example:

Java

import java.math.BigInteger;

public class Example { public static void main(String[] args) { BigInteger BigInteger1 = new BigInteger("3515219485"); BigInteger BigInteger2 = new BigInteger("3515219485");

sql
BigInteger result = BigInteger1.mod(BigInteger2); System.out.println("The remainder of BigInteger1 divided by BigInteger2 is: " + result); }

}

Output: The remainder of BigInteger1 divided by BigInteger2 is: 0

If BigInteger2 is less than or equal to zero, the mod() method throws an ArithmeticException. Here is an example:

Java

import java.math.BigInteger;

public class Example { public static void main(String[] args) { BigInteger BigInteger1 = new BigInteger("3515219485"); BigInteger BigInteger2 = new BigInteger("-1711");

sql
BigInteger result = BigInteger1.mod(BigInteger2); System.out.println("The remainder of BigInteger1 divided by BigInteger2 is: " + result); }

}

Output: Exception in thread "main" java.lang.ArithmeticException: BigInteger: modulus not positive at java.math.BigInteger.mod(BigInteger.java:2458) at Example.main(Example.java:9)

In this example, we created two BigInteger objects called BigInteger1 and BigInteger2. We then tried to call the mod() method on BigInteger1 and pass BigInteger2 as the parameter. However, since BigInteger2 is less than or equal to zero, the mod() method threw an ArithmeticException.

Previous Post Next Post