java.math.BigInteger divideAndRemainder(BigInteger val)
Description
On this document we will be showing a java example on how to use the divideAndRemainder(BigInteger val) method of BigInteger Class. Basically this method return an array of BigInteger with being the first one be the quotient(same as the result if we use the divide method) while the second index corresponds to the remainder(same as performing the operation on the primitive int data type n%n1. If you are only interested on the quotient I am recommending to use the divide() method of BigInteger class too.
Notes:
- this method throws an ArithmeticException when the val method argument supplied is zero.
Method Syntax
public BigInteger[] divideAndRemainder(BigInteger val)
Method Argument
Data Type | Parameter | Description |
---|---|---|
BigInteger | val | value by which this BigInteger is to be divided. |
Method Returns
The divideAndRemainder(BigInteger val) method returns an array of two BigIntegers: the quotient (this / val) is the initial element, and the remainder (this % val) is the final element.
Compatibility
Requires Java 1.1 and up
Java BigInteger divideAndRemainder() Example
Below is a java code demonstrates the use of divideAndRemainder(BigInteger val) method of BigInteger class. The example presented might be simple however it shows the behavior of the divideAndRemainder() method.
package com.javatutorialhq.java.examples; import java.math.BigInteger; import java.util.Scanner; /* * A java example source code to demonstrate * the use of divideAndRemainder() method of BigInteger class */ public class BigIntegerDivideAndRemainderExample { public static void main(String[] args) { // ask for user input System.out.print("Enter the dividend:"); Scanner s = new Scanner(System.in); String dividend = s.nextLine(); System.out.print("Enter the divisor:"); String divisor = s.nextLine(); s.close(); // convert the string input to BigInteger BigInteger val1 = new BigInteger(dividend); BigInteger val2 = new BigInteger(divisor); // get the quotient BigInteger[] result = val1.divideAndRemainder(val2); BigInteger quotient = result[0]; BigInteger remainder = result[1]; System.out.println("Result of the operation is:" + quotient + " r " + remainder); } }
This example is a lot simpler than it looks. We simply ask the user for two inputs, the first one is the dividend and the other is divisor. The quotient and remainder were derived in using the divideAndRemainder() method of the BigInteger class.