Open In App

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

Last Updated : 28 Jan, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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-



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads