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


Java BigInteger gcd()用法及代碼示例


兩個數字的GCD(最大公因數)或HCF(最大公因數)是將兩者相除的最大數。 java.math.BigInteger.gcd(BigInteger val)方法用於計算兩個BigInteger的gcd。此方法根據當前的BigInteger計算gcd,調用該方法並通過BigInteger作為參數

用法:

public BigInteger gcd(BigInteger val)

參數:此方法接受參數val,它是要計算其gcd的兩個數字之一。該數字應為BigInteger類型。


返回值:此方法返回一個BigInteger,其中保存兩個BigInteger的計算出的gcd。

下麵的程序用於說明BigInteger的gcd()方法。

示例1:

// Java program to demonstrate 
// gcd() method of BigInteger 
  
import java.math.BigInteger; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // BigInteger object to store the result 
        BigInteger result; 
  
        // For user input 
        // Use Scanner or BufferedReader 
  
        // Two objects of String created 
        // Holds the values to calculate gcd 
        String input1 = "54"; 
        String input2 = "42"; 
  
        // Creating two BigInteger objects 
        BigInteger a 
            = new BigInteger(input1); 
        BigInteger b 
            = new BigInteger(input2); 
  
        // Calculate gcd 
        result = a.gcd(b); 
  
        // Print result 
        System.out.println("The GCD of "
                           + a + " and "
                           + b + " is "
                           + result); 
    } 
}
輸出:
The GCD of 54 and 42 is 6

示例2:

// Java program to demonstrate 
// gcd() method of BigInteger 
  
import java.math.BigInteger; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // BigInteger object to store result 
        BigInteger result; 
  
        // For user input 
        // Use Scanner or BufferedReader 
  
        // Two objects of String 
        // Holds the values to calculate gcd 
        String input1 = "4095484568135646548"; 
        String input2 = "9014548534231345454"; 
  
        // Creating two BigInteger objects 
        BigInteger a 
            = new BigInteger(input1); 
        BigInteger b 
            = new BigInteger(input2); 
  
        // Calculate gcd 
        result = a.gcd(b); 
  
        // Print result 
        System.out.println("The GCD of "
                           + a + " and "
                           + b + " is "
                           + result); 
    } 
}
輸出:

The GCD of 4095484568135646548 and 9014548534231345454 is 2

參考: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigInteger.html#gcd(java.math.BigInteger)



相關用法


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