C 编程:寻找两个数字的最小公倍数
为了理解这个例子,你应该具备以下 C 语言编程 方面的知识:
两个整数 n1
和 n2
的最小公倍数(LCM)是可以整除 n1
和 n2
(无余数)的最小正整数。例如,72 和 120 的最小公倍数是 360。
使用 while 和 if 计算最小公倍数
#include <stdio.h>
int main() {
int n1, n2, max;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
// 将 n1 和 n2 中的较大数存储在 max 中
max = (n1 > n2) ? n1 : n2;
while (1) {
if ((max % n1 == 0) && (max % n2 == 0)) {
printf("The LCM of %d and %d is %d.", n1, n2, max);
break;
}
++max;
}
return 0;
}
输出
Enter two positive integers: 72
120
The LCM of 72 and 120 is 360.
在这个程序中,用户输入的整数分别存储在变量 n1
和 n2
中。
变量 max
中存储了 n1
和 n2
中的较大数。两个数的最小公倍数不会小于 max
。
while
循环的测试表达式始终为 true。
在每次迭代中,我们检查 max
是否能被 n1
和 n2
完整除尽。
if ((max % n1 == 0) && (max % n2 == 0)) {
// 代码
}
如果这个测试条件不成立,max
就增加 1,迭代继续,直到 if
语句的测试表达式为真。
使用最大公约数计算最小公倍数
我们也可以使用两个数 num1
和 num2
的最大公约数(GCD)来找到它们的最小公倍数:
LCM = (num1 * num2) / GCD
在用这种方法找到最小公倍数之前,了解如何在 C 语言中找到两个数的最大公约数。
#include <stdio.h>
int main() {
int n1, n2, i, gcd, lcm;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
// 循环找到最大公约数
for (i = 1; i <= n1 && i <= n2; ++i) {
// 检查 i 是否是两个整数的因数
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.