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

My Personal Notes arrow_drop_up In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.