Java BigInteger Class | divideAndRemainder() Method with Example

BigInteger Class divideAndRemainder() method: Here, we are going to learn about the divideAndRemainder() method of BigInteger Class with its syntax and example.
Submitted by Preeti Jain, on May 10, 2020

BigInteger Class divideAndRemainder() method

  • divideAndRemainder() method is available in java.math package.
  • divideAndRemainder() method returns BigInteger array of 2 elements that contain quotient that is calculated by using (this BigInteger)/(BigInteger val) followed by the remainder that is calculated by using (this BigInteger) % (BigInteger val).
  • divideAndRemainder() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • divideAndRemainder() method may throw an exception at the time of calculating the remainder.
    ArithmeticException: This exception may throw when the given parameter holds value 0.

Syntax:

    public BigInteger[] divideAndRemainder(BigInteger val);

Parameter(s):

  • BigInteger val – represents the value by which this BigInteger is to be divided and generate remainder.

Return value:

The return type of this method is BigInteger[], it returns an array of BigInteger of two element of "BigInteger" type and the quotient is calculated by using (this BigInteger)/ (BigInteger val) and the remainder is calculated by using (this BigInteger) % (BigInteger val).

Example:

// Java program to demonstrate the example 
// of divideAndRemainder(BigInteger val)  method of BigInteger

import java.math.*;

public class DivideAndRemainderOfBI {
    public static void main(String args[]) {
        // Initialize two variables divi, divisr
        String divi = "120";
        String divisr = "4";

        // Initialize two BigInteger objects 
        BigInteger b_int1 = new BigInteger(divi);
        BigInteger b_int2 = new BigInteger(divisr);

        // Display b_int1 and b_int2
        System.out.println("b_int1: " + b_int1);
        System.out.println("b_int2: " + b_int2);
        
        System.out.println("divideAndRemainder(BigInteger): ");

        // divides this BigInteger (b_int1) by the
        // given BigInteger (b_int2) and return the BigInteger[]
        // of two values (Quotient, Remainder)
        BigInteger[] div_rem = b_int1.divideAndRemainder(b_int2);
        System.out.println("Quotient div_rem[0]: " + div_rem[0]);
        System.out.println("Remainder div_rem[1]: " + div_rem[1]);
    }
}

Output

b_int1: 120
b_int2: 4
divideAndRemainder(BigInteger): 
Quotient div_rem[0]: 30
Remainder div_rem[1]: 0


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.