当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。