兩個數字的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 BigInteger add()用法及代碼示例
- Java BigInteger isProbablePrime()用法及代碼示例
- Java BigInteger sqrtAndRemainder()用法及代碼示例
- Java BigInteger multiply()用法及代碼示例
- Java 8 BigInteger divideAndRemainder()用法及代碼示例
- Java BigInteger subtract()用法及代碼示例
- Java BigInteger nextProbablePrime()用法及代碼示例
- Java 8 BigInteger byteValueExact()用法及代碼示例
- Java 8 BigInteger longValueExact()用法及代碼示例
- Java BigInteger intValueExact()用法及代碼示例
- Java BigInteger divide()用法及代碼示例
- Java 8 BigInteger shortValueExact()用法及代碼示例
- Java BigInteger abs()用法及代碼示例
- Java BigInteger or()用法及代碼示例
- Java BigInteger mod()用法及代碼示例
注:本文由純淨天空篩選整理自Rajnis09大神的英文原創作品 BigInteger gcd() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。