C语言求两个数最小公倍数的程序

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


两个整数 n1n2 的最小公倍数(LCM)是能同时被 n1n2 整除的最小正整数(无余数)。例如,72120 的最小公倍数是 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.

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

n1n2 中较大的数存储在 max 中。两个数的最小公倍数不可能小于 max

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

在每次迭代中,我们检查 max 是否能被 n1n2 整除。

if ((max % n1 == 0) && (max % n2 == 0)) {
    // code
}

如果该测试条件不为真,则 max 增加1,迭代继续,直到 if 语句的测试表达式为真。


使用 GCD 计算 LCM

我们还可以使用两个数 num1num2 的 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.
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战