Skip to content

Latest commit

 

History

History
105 lines (72 loc) · 2.42 KB

78.md

File metadata and controls

105 lines (72 loc) · 2.42 KB

C 程序:查找两个数字的 LCM

原文: https://www.programiz.com/c-programming/examples/lcm

在此示例中,您将学习如何计算用户输入的两个数字的 LCM(最小公倍数)。

要理解此示例,您应该了解以下 C 编程主题:


两个整数n1n2的 LCM 是可被n1n2完全除尽的最小正整数。 )。 例如,LCM 为 72 和 120 为 360。


LCM 使用whileif

#include <stdio.h>
int main() {
    int n1, n2, min;
    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);

    // maximum number between n1 and n2 is stored in min
    min = (n1 > n2) ? n1 : n2;

    while (1) {
        if (min % n1 == 0 && min % n2 == 0) {
            printf("The LCM of %d and %d is %d.", n1, n2, min);
            break;
        }
        ++min;
    }
    return 0;
} 

输出

Enter two positive integers: 72
120
The LCM of 72 and 120 is 360. 

在该程序中,用户输入的整数分别存储在变量n1n2中。

min中存储了n1n2中最大的数目。 两个数字的 LCM 不能小于min

while循环的测试表达式始终为true

在每次迭代中,检查min是否可被n1n2完全整除。

if (min % n1 == 0 && min % n2 == 0) { ... }

如果此测试条件不成立,则将min递增1,并且迭代将继续进行,直到if语句的测试表达式为true

也可以使用以下公式找到两个数字的 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.