當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Guava LongMath gcd(long a, long b)用法及代碼示例


Guava LongMath類的方法gcd(long a,long b)返回兩個參數a和b的最大公約數。

用法:

public static long gcd(long a, long b)

參數:此方法接受要查找其GCD的long類型的兩個參數a和b。


返回類型:此方法返回最大的正long值,該值將傳遞給函數的兩個參數相除。

異常:如果a為負數或b為負數,則方法gcd(long a,long b)拋出IllegalArgumentException。

注意:如果a和b均為零,則該方法返回零。

範例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-



相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Java Guava | gcd(long a, long b) of LongMath Class with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。