C program to print LCM of two numbers

C program to print LCM of two numbers

In this tutorial, you will learn how to write a program to print LCM of two numbers by using for loop conditional statement.

Our problem statement:

Here, we have to find LCM for the two user-given numbers. Least common multiple or LCM is the value that is evenly divisible by the two given numbers.

For Example:

Input: 76 and 89

Output: 6764

As, both 76 and 89 will evenly divide 6764.

In the below code, we are using for-loop to iterate the given numbers and checking the divisibility for both the numbers for that iteration. When we reach an iteration where the conditions are met we break the loop for our output.


#include <stdio.h>
int main() {
    int num1, num2, lcm, max;
    printf("Enter two positive integers: ");
    scanf("%d %d", &num1, &num2);
        max = (num1 > num2) ? num1 : num2;
        for (lcm = max; ; lcm += max) {
        if (lcm % num1 == 0 && lcm % num2 == 0) {
            printf("LCM of %d and %d is %d", num1, num2, lcm);
            break;
        }
    }
    return 0;
}

Output:

Enter two positive integers: 76
89
LCM of 76 and 89 is 6764