Java BigInteger gcd()方法及实例

Java BigInteger gcd()方法及实例

两个数字的GCD(Greatest Common Divisor)或HCF(Highest Common Factor)是除以这两个数字的最大数字。 java.math.BigInteger .gcd(BigInteger val) 方法用于计算两个BigIntegers的gcd。该方法在调用该方法的当前BigInteger和作为参数传递的BigInteger上计算gcd。

语法 :

public BigInteger gcd(BigInteger val)

参数: 该方法接受一个参数val,它是两个数字中的一个,其gcd将被计算。这个数字应该是BigInteger类型的。

返回值: 该方法返回一个 BigInteger ,其中包含两个BigIntegers的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)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程