Java BigInteger Class | gcd() Method with Example

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

BigInteger Class gcd() method

  • gcd() method is available in java.math package.
  • gcd() method is used to return the greatest common divisor of the absolute of this BigInteger and the given parameter (val).
  • gcd() 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.
  • gcd() method does not throw an exception at the time of finding GCD.

Syntax:

    public BigInteger gcd(BigInteger val);

Parameter(s):

  • BigInteger val – represents the value of which the GCD is to calculate with this BigInteger.

Return value:

The return type of this method is BigInteger, it returns BigInteger and its value is to returned in terms of GCD of abs(this BigInteger) and abs(BigInteger val).

Example:

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

import java.math.*;

public class GCDOfBI {
    public static void main(String args[]) {
        // Initialize two variables str1 and str2
        String str1 = "30";
        String str2 = "50";

        // Initialize two BigInteger objects  
        BigInteger b_int1 = new BigInteger(str1);
        BigInteger b_int2 = new BigInteger(str2);

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

        // calculates greatest common divisors
        // (gcd) of two BigInteger values like
        // b_int1.gcd(b_int2) 
        BigInteger gcd = b_int1.gcd(b_int2);
        System.out.println("b_int1.gcd(b_int2): " + gcd);
    }
}

Output

b_int1: 30
b_int2: 50
b_int1.gcd(b_int2): 10


Comments and Discussions!

Load comments ↻





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