LCM of Two Numbers Program in C Language

To find the LCM of two numbers in C programming, take largest of the two numbers in lcm, and increment lcm till their product, wherein during each increment check if lcm does not leave any reminder when divided by the given two numbers.

Second method of find LCM is using LCM formula with HCF, where LCM = (product of given two numbers) / HCF.

Method 1

In the following program, we read two numbers to n1 and n2, and find their LCM.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int n1, n2;
    printf("Enter first  number : ");
    scanf("%d", &n1);
    printf("Enter second number : ");
    scanf("%d", &n2);
    
    int lcm;
    lcm = (n1 > n2) ? n1 : n2;

    do {
        if (lcm % n1 == 0 && lcm % n2 == 0) {
            break;
        }
        else {
            lcm++;
        }
    } while (lcm < (n1 * n2));
    
    printf("LCM : %d\n", lcm);
}

Output

Enter first  number : 12
Enter second number : 30
LCM : 60
Program ended with exit code: 0

Output

Enter first  number : 10
Enter second number : 20
LCM : 20
Program ended with exit code: 0

Method 2

In the following program, we read two numbers to n1 and n2, and find their HCF. Using HCF we compute LCM using the formula.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int n1, n2;
    printf("Enter first  number : ");
    scanf("%d", &n1);
    printf("Enter second number : ");
    scanf("%d", &n2);
    
    int hcf = n1, temp = n2;
    while(hcf != temp) {
        if(hcf > temp)
            hcf = hcf - temp;
        else
            temp = temp - hcf;
    }
    
    int lcm = (n1 * n2) / hcf;
    
    printf("LCM : %d\n", lcm);
}

Output

Enter first  number : 12
Enter second number : 30
LCM : 60
Program ended with exit code: 0

Output

Enter first  number : 10
Enter second number : 20
LCM : 20
Program ended with exit code: 0

Conclusion

In this C Tutorial, we learned how to find LCM of two numbers in C programming, with example programs.