Thursday, October 23, 2025
HomeLanguagesJavaJava Guava | gcd(long a, long b) of LongMath Class with Examples

Java Guava | gcd(long a, long b) of LongMath Class with Examples

The method gcd(long a, long b) of Guava’s LongMath Class returns the greatest common divisor of two parameters a and b.

Syntax:

public static long gcd(long a, long b)

Parameters: This method accepts two parameters a and b of the long type of whose GCD is to be found.

Return Type: This method returns the largest positive long value that divides both of the parameters passed to the function.

Exceptions: The method gcd(long a, long b) throws IllegalArgumentException if a is negative or b is negative.

Note: If a and b both are zero, the method returns zero.

Example 1:




// Java code to show implementation of
// gcd(long a, long b) method of Guava's
// LongMath class
  
import java.math.RoundingMode;
import com.google.common.math.LongMath;
  
class GFG {
  
    // Driver code
    public static void main(String args[])
    {
        long a1 = 14;
        long b1 = 70;
  
        // Using gcd(long a, long b) method
        // of Guava's LongMath class
        long ans1 = LongMath.gcd(a1, b1);
  
        System.out.println("GCD of " + a1
                           + " and " + b1
                           + " is " + ans1);
  
        long a2 = 23;
        long b2 = 15;
  
        // Using gcd(long a, long b) method
        // of Guava's LongMath class
        long ans2 = LongMath.gcd(a2, b2);
  
        System.out.println("GCD of " + a2
                           + " and " + b2
                           + " is " + ans2);
    }
}


Output:

GCD of 14 and 70 is 14
GCD of 23 and 15 is 1

Example 2:




// Java code to show implementation of
// gcd(long a, long b) method of Guava's
// LongMath class
  
import java.math.RoundingMode;
import com.google.common.math.LongMath;
  
class GFG {
  
    // Driver code
    public static void main(String args[])
    {
        long a = -5;
        long b = 15;
  
        try {
            // Using gcd(long a, long b) method
            // of Guava's LongMath class
            // This should throw "IllegalArgumentException"
            // as a < 0
            long ans = LongMath.gcd(a, b);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output:

java.lang.IllegalArgumentException: a (-5) must be >= 0

Reference: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/LongMath.html#gcd-long-long-

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS