两个整数的 LCM 是能被两个数完全整除的最小正整数(没有余数)。
示例 1: LCM 使用 while 循环和 if 语句
public class Main { public static void main(String[] args) { int n1 = 72, n2 = 120, lcm; // maximum number between n1 and n2 is stored in lcm lcm = (n1 > n2) ? n1 : n2; // Always true while(true) { if( lcm % n1 == 0 && lcm % n2 == 0 ) { System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm); break; } ++lcm; } } }
输出
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, gcd = 1; for(int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if(n1 % i == 0 && n2 % i == 0) gcd = i; } int lcm = (n1 * n2) / gcd; System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm); } }
该程序的输出与示例 1 相同。
在这里,在 for 循环中,我们计算两个数字-
n1 和
n2 的 GCD。计算后,我们用上面的公式来计算LCM。