两个整数 n1 和 n2 的最小公倍数(LCM)是能同时被 n1 和 n2 整除的最小正整数(无余数)。例如,72 和 120 的最小公倍数是 360。
使用 while 和 if 计算最小公倍数
#include <stdio.h>
int main() {
int n1, n2, max, lcm;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
// maximum number between n1 and n2 is stored in max
max = (n1 > n2) ? n1 : n2;
lcm = max;
while ((lcm % n1 != 0) || (lcm % n2 != 0)) {
lcm += max;
}
printf("The LCM of %d and %d is %d.", n1, n2, lcm);
return 0;
}
输出
Enter two positive integers: 72 120 The LCM of 72 and 120 is 360.
在此程序中,用户输入的整数分别存储在变量 n1 和 n2 中。
n1 和 n2 中较大的数存储在 max 中。两个数的最小公倍数不可能小于 max。
while
循环的测试表达式始终为真。
在每次迭代中,我们检查 max 是否能被 n1 和 n2 整除。
if ((max % n1 == 0) && (max % n2 == 0)) {
// code
}
如果该测试条件不为真,则 max 增加1,迭代继续,直到 if
语句的测试表达式为真。
使用 GCD 计算 LCM
我们还可以使用两个数 num1 和 num2 的 GCD 来找到它们的 LCM
LCM = (num1 * num2) / GCD
在学习此方法计算 LCM 之前,请先学习 如何在 C 语言中找到两个数的 GCD。
#include <stdio.h>
int main() {
int n1, n2, i, gcd, lcm;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
// loop to find the GCD
for (i = 1; i <= n1 && i <= n2; ++i) {
// check if i is a factor of both integers
if (n1 % i == 0 && n2 % i == 0)
gcd = i;
}
lcm = (n1 * n2) / gcd;
printf("The LCM of two numbers %d and %d is %d.", n1, n2, lcm);
return 0;
}
输出
Enter two positive integers: 72 120 The LCM of two numbers 72 and 120 is 360.