小張帶領 3 個開發組加班,想給每組發一袋核桃,要求:
輸入:三個正整數 a, b, c(< 30),分別為三組人數。
輸出:每袋核桃最少數量。
| 輸入 | 輸出 | 說明 |
|---|---|---|
| 2 4 5 | 20 | LCM(2,4,5)=20 |
| 3 1 1 | 3 | LCM(3,1,1)=3 |
每組人數為 a, b, c,核桃數需能被三者整除 → 求 LCM(a, b, c)。
數學公式:LCM(x, y) = x * y / GCD(x, y),三數遞推:LCM(a, b, c) = LCM(LCM(a, b), c)。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] a = new int[3];
for (int i = 0; i < 3; i++) a[i] = in.nextInt();
// 可選:排序優化(非必需)
java.util.Arrays.sort(a);
int lcm = lcm(a[0], a[1]);
lcm = lcm(lcm, a[2]);
System.out.println(lcm);
}
// 輾轉相除法求最大公約數
private static int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
// 最小公倍數
private static int lcm(int x, int y) {
return x / gcd(x, y) * y; // 先除後乘防溢出
}
}
x * y 可能超範圍,建議 x / gcd * y 先除後乘這道題考察基礎數論與代碼實現能力,掌握 GCD → LCM 模板,同類「最小公倍數」「齊次同步」問題(如燈光同步、行星對齊)皆可秒殺。