This tutorial will teach you how to find the LCM (Least Common Multiple) of two numbers in C. To understand this example, you should have knowledge of the following C programming topics.
The LCM (Least Common Multiple) of two integers is the smallest positive integer that is perfectly divisible by both the numbers (without a remainder). For example, the LCM of 30 and 40 is 120.
Find LCM in C using loop
#include <stdio.h>
int main()
{
int num1, num2, largest;
printf("Enter 2 positive integers:\n");
scanf("%d %d", &num1, &num2);
//the largest among these two is stored in largest
largest = (num1 > num2) ? num1 : num2;
while (1) //always true
{
if (largest % num1 == 0 && largest % num2 == 0)
{
printf("The LCM of %d and %d is: %d", num1, num2, largest);
break;
}
++largest;
}
return 0;
}
Output:
Enter 2 positive integers:
30
40
The LCM of 30 and 40 is: 120
C Program to Find LCM using GCD
#include <stdio.h>
int main()
{
int num1, num2, i, gcd, lcm;
printf("Enter 2 positive integers:\n");
scanf("%d %d", &num1, &num2);
for (i = 1; i <= num1 && i <= num2; ++i)
{
// check if i is a factor of both integers
if (num1 % i == 0 && num2 % i == 0)
gcd = i;
}
lcm = (num1 *num2) / gcd; //use of gcd
printf("The LCM of %d and %d: %d", num1, num2, lcm);
return 0;
}
Output:
Enter 2 positive integers:
30
40
The LCM of 30 and 40: 120