How to find the least common multiple in the C language?

One way to find the least common multiple of two numbers is by first finding their greatest common divisor and then dividing the product of the two numbers by the greatest common divisor.

Here is an example of C code for finding the least common multiple.

#include <stdio.h>

// 求两个数的最大公约数
int gcd(int a, int b) {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}

// 求两个数的最小公倍数
int lcm(int a, int b) {
    int gcdValue = gcd(a, b);
    return a * b / gcdValue;
}

int main() {
    int num1, num2;
    printf("请输入两个数:");
    scanf("%d %d", &num1, &num2);
    int result = lcm(num1, num2);
    printf("最小公倍数为:%d\n", result);
    return 0;
}

The gcd function in the above code is used to find the greatest common divisor of two numbers through recursive calling. The lcm function finds the least common multiple by calling the gcd function to calculate the greatest common divisor, and then dividing the product of the two numbers by the greatest common divisor.

In the main function, first obtain two numbers from user input, then call the lcm function to find the least common multiple, and finally output the result.

Leave a Reply 0

Your email address will not be published. Required fields are marked *