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
参考: Java : Java(Java )