Guava – LongMath.gcd方法与实例

Guava – LongMath.gcd方法与实例

Guava的LongMath类的gcd(long a, long b)方法返回两个参数a和b的最大公除数。

语法:

public static long gcd(long a, long b)

参数: 该方法接受两个参数a和b,这两个参数都是要寻找GCD的长类型.

返回值: 该方法返回最大的正长值,该值除以传递给函数的两个参数.

异常: 如果a是负数或者b是负数,gcd(long a, long b)方法会抛出IllegalArgumentException.

注意: 如果a和b都是0,该方法返回0.

实例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);
    }
}

输出:

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

实例 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);
        }
    }
}

输出:

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

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程