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


Java Guava IntMath gcd(int a, int b)用法及代碼示例


Guava IntMath類的方法gcd(int a,int b)返回a,b的最大公約數。

用法:

public static int gcd(int a, int b)

Where a and b are integers.

返回值:整數a和b的最大公約數。


異常:如果a <0或b <0,則方法gcd(int a,int b)拋出IllegalArgumentException。

範例1:

// Java code to show implementation of 
// gcd(int a, int b) method of Guava's 
// IntMath class 
import java.math.RoundingMode; 
import com.google.common.math.IntMath; 
  
class GFG { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        int a1 = 64; 
        int b1 = 36; 
  
        // Using gcd(int a, int b) method 
        // of Guava's IntMath class 
        int ans1 = IntMath.gcd(a1, b1); 
  
        System.out.println("GCD of a1 & b1 is:"
                           + ans1); 
  
        int a2 = 23; 
        int b2 = 15; 
  
        // Using gcd(int a, int b) method 
        // of Guava's IntMath class 
        int ans2 = IntMath.gcd(a2, b2); 
  
        System.out.println("GCD of a2 & b2 is:"
                           + ans2); 
    } 
}
輸出:
GCD of a1 & b1 is:4
GCD of a2 & b2 is:1

範例2:

// Java code to show implementation of 
// gcd(int a, int b) method of Guava's 
// IntMath class 
import java.math.RoundingMode; 
import com.google.common.math.IntMath; 
  
class GFG { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        int a1 = -5; 
        int b1 = 15; 
  
        try { 
            // Using gcd(int a, int b) method 
            // of Guava's IntMath class 
            // This should throw "IllegalArgumentException" 
            // as a1 < 0 
            int ans1 = IntMath.gcd(a1, b1); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
輸出:
java.lang.IllegalArgumentException:a (-5) must be >= 0

注意:如果a == 0 && b == 0,則該方法返回0。

參考: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#gcd-int-int-



相關用法


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