Java.math.BigInteger.gcd() Method



Description

The java.math.BigInteger.gcd(BigInteger val) returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val). It returns 0 if this == 0 && val == 0.

Declaration

Following is the declaration for java.math.BigInteger.gcd() method.

public BigInteger gcd(BigInteger val)

Parameters

val − Value with which the GCD is to be computed.

Return Value

This method returns a BigInteger whose value is GCD(abs(this), abs(val)).

Exception

NA

Example

The following example shows the usage of math.BigInteger.gcd() method.

package com.tutorialspoint;

import java.math.*;

public class BigIntegerDemo {

   public static void main(String[] args) {

      // create 3 BigInteger objects
      BigInteger bi1, bi2, bi3;

      // assign values to bi1, bi2
      bi1 = new BigInteger("18");
      bi2 = new BigInteger("24");

      // assign gcd of bi1, bi2 to bi3
      bi3 = bi1.gcd(bi2);

      String str = "GCD of " + bi1 + " and " + bi2 + " is " +bi3;

      // print bi3 value
      System.out.println( str );
   }
}

Let us compile and run the above program, this will produce the following result −

GCD of 18 and 24 is 6
java_math_biginteger.htm
Advertisements