在Java中,計算兩個數的最大公約數(Greatest Common Divisor, GCD)和最小公倍數(Least Common Multiple, LCM)是常見的編程問題。以下是具體的實現方法和代碼示例。
---
### **1. 最大公約數 (GCD)**
最大公約數是指兩個或多個整數共有約數中最大的一個。常用的方法有:
#### **方法 1:輾轉相除法(歐幾里得算法)**
這是求解最大公約數的經典算法,其核心思想是通過遞歸或循環不斷取余數,直到余數為0為止。
**公式**:
- 如果 `a % b == 0`,則 `GCD(a, b) = b`。
- 否則,`GCD(a, b) = GCD(b, a % b)`。
#### **代碼實現**:
```java
public class GCDCalculator {
? ? // 使用輾轉相除法計算最大公約數
? ? public static int gcd(int a, int b) {
? ? ? ? while (b != 0) {
? ? ? ? ? ? int temp = b;
? ? ? ? ? ? b = a % b;
? ? ? ? ? ? a = temp;
? ? ? ? }
? ? ? ? return a;
? ? }
? ? public static void main(String[] args) {
? ? ? ? int num1 = 56;
? ? ? ? int num2 = 98;
? ? ? ? System.out.println("最大公約數: " + gcd(num1, num2)); // 輸出 14
? ? }
}
```
---
### **2. 最小公倍數 (LCM)**
最小公倍數是指兩個或多個整數的最小正整數倍數。最小公倍數可以通過最大公約數計算得出。
**公式**:
- `LCM(a, b) = (a * b) / GCD(a, b)`
#### **代碼實現**:
```java
public class LCMCalculator {
? ? // 使用輾轉相除法計算最大公約數
? ? public static int gcd(int a, int b) {
? ? ? ? while (b != 0) {
? ? ? ? ? ? int temp = b;
? ? ? ? ? ? b = a % b;
? ? ? ? ? ? a = temp;
? ? ? ? }
? ? ? ? return a;
? ? }
? ? // 計算最小公倍數
? ? public static int lcm(int a, int b) {
? ? ? ? return (a * b) / gcd(a, b);
? ? }
? ? public static void main(String[] args) {
? ? ? ? int num1 = 56;
? ? ? ? int num2 = 98;
? ? ? ? System.out.println("最大公約數: " + gcd(num1, num2)); // 輸出 14
? ? ? ? System.out.println("最小公倍數: " + lcm(num1, num2)); // 輸出 392
? ? }
}
```
---
### **3. 示例運行結果**
假設輸入兩個數為 `56` 和 `98`:
- 最大公約數:`gcd(56, 98) = 14`
- 最小公倍數:`lcm(56, 98) = (56 * 98) / 14 = 392`
輸出結果:
```
最大公約數: 14
最小公倍數: 392
```
---
### **4. 注意事項**
1. **輸入驗證**:
? ?- 確保輸入的數字是正整數。
? ?- 如果輸入可能為負數或零,需要進行額外處理。
2. **溢出問題**:
? ?- 在計算 `(a * b)` 時,可能會導致整數溢出。如果可能遇到大數,可以使用 `long` 類型或 `BigInteger` 類。
#### **使用 BigInteger 的實現**:
```java
import java.math.BigInteger;
public class GCDCalculatorWithBigInteger {
? ? public static BigInteger gcd(BigInteger a, BigInteger b) {
? ? ? ? return a.gcd(b); // BigInteger 提供了內置的 gcd 方法
? ? }
? ? public static BigInteger lcm(BigInteger a, BigInteger b) {
? ? ? ? return a.multiply(b).divide(gcd(a, b));
? ? }
? ? public static void main(String[] args) {
? ? ? ? BigInteger num1 = new BigInteger("56");
? ? ? ? BigInteger num2 = new BigInteger("98");
? ? ? ? System.out.println("最大公約數: " + gcd(num1, num2)); // 輸出 14
? ? ? ? System.out.println("最小公倍數: " + lcm(num1, num2)); // 輸出 392
? ? }
}
```
---
### **總結**
1. **最大公約數**:使用輾轉相除法(歐幾里得算法)。
2. **最小公倍數**:利用公式 `LCM(a, b) = (a * b) / GCD(a, b)`。
3. **注意事項**:處理溢出問題,確保輸入合法。
通過以上代碼和方法,你可以輕松地在Java中實現最大公約數和最小公倍數的計算!如果有其他問題,歡迎繼續提問!