查找两个数字的最小公倍数的 C 程序
本文使用 C 语言中的循环和 if 语句计算两个整数(正整数和负整数)的最小公倍数。
要理解此示例,您应该具备以下 C 语言编程主题的知识:
两个整数 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);
// maximum number between n1 and n2 is stored in 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
。
n1
和 n2
中最大的数字存储在变量 max
中, 两个数的最小公倍数不能小于 max
.
while
循环的的测试表达式始终为真。
在每次迭代中,检查 max
是否可以被 n1
和 n2
整除。
if (min % n1 == 0 && max% n2 == 0) { ... }
如果这个测试条件不成立, max
递增 1
并且迭代继续,直到 if
语句的测试表达式为真。
也可以使用以下公式找到两个数字的 LCM:
最小公倍数 = (num1 * num2) / 最大公约数
了解如何在 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) {
// 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.