两个整数的最小公倍数 (LCM) 是能被这两个数整除的最小正整数(没有余数)。
示例 1: 使用 while 循环和 if 语句计算 LCM
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n1 = 72, n2 = 120;
int gcd = findGCD(n1, n2);
int lcm = (n1 * n2) / gcd;
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
}
public static int findGCD(int a, int b) {
if (b == 0)
return a;
return findGCD(b, a % b);
}
}
输出
The LCM of 72 and 120 is 360.
在此程序中,需要计算 LCM 的两个数字分别存储在变量 n1 和 n2 中。
然后,我们将 lcm 初始化为这两个数字中较大的一个。这是因为 LCM 不可能小于较大的那个数。
在无限 while 循环 (while(true)
) 中,我们检查 lcm 是否能被 n1 和 n2 整除。
如果可以,我们就找到了 LCM。我们打印 LCM 并使用 break
语句跳出 while 循环。
否则,我们将 lcm 增加 1 并重新测试整除条件。
我们也可以使用 GCD 来找到两个数的 LCM,方法如下:
LCM = (n1 * n2) / GCD
如果您不知道如何在 Java 中计算 GCD,请查看 Java 程序计算两个数的 GCD。
示例 2: 使用 GCD 计算 LCM
public class Main {
public static void main(String[] args) {
int n1 = 72, n2 = 120;
int gcd = findGCD(n1, n2);
int lcm = (n1 * n2) / gcd;
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
}
public static int findGCD(int a, int b) {
if (b == 0)
return a;
return findGCD(b, a % b);
}
}
此程序的输出与示例 1 相同。
在这里,在 for 循环中,我们计算了两个数字 n1 和 n2 的 GCD。计算完成后,我们使用上述公式计算 LCM。