 # C Program to Find LCM of two Numbers

In this example, you will learn to calculate the LCM (Lowest Common Multiple) of two numbers entered by the user.

To understand this example, you should have the knowledge of the following C programming topics:

The LCM of two integers n1 and n2 is the smallest positive integer that is perfectly divisible by both n1 and n2 (without a remainder). For example, the LCM of 72 and 120 is 360.

## LCM using while and if

``````#include <stdio.h>

int main() {

int n1, n2, max;

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;

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

Output

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

In this program, the integers entered by the user are stored in variable n1 and n2 respectively.

The largest number among n1 and n2 is stored in max. The LCM of two numbers cannot be less than max.

The test expression of `while` loop is always true.

In each iteration, we check whether max is perfectly divisible by n1 and n2.

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

If this test condition is not true, max is incremented by 1 and the iteration continues until the test expression of the `if` statement is true.

## LCM Calculation Using GCD

We can also find the LCM of two numbers num1 and num2 using their GCD:

`LCM = (num1 * num2) / GCD`

Learn how to find the GCD of two numbers in C programming before finding the LCM with this method.

``````#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;
}``````

Output

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