两个整数
n1 和
n2 的 LCM 是可以被
n1 和
n2
<完全整除的最小正整数 var>
(没有余数)。比如72和120的LCM就是360。
完全整除的最小正整数>
LCM 使用 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 中。两个数的 LCM 不能小于
max。
while
循环的测试表达式始终为真。
在每次迭代中,检查
max 是否可以被
n1 和
n2 完全整除。
if (min % n1 == 0 && max% n2 == 0) { ... }
如果这个测试条件不成立,
max 增加
1
并继续迭代,直到
if
语句的测试表达式为真的。
两个数字的 LCM 也可以使用以下公式找到:
LCM = (num1*num2)/GCD
了解如何在 C 编程中找到两个数字的 GCD。
使用 GCD 进行 LCM 计算
#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.