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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #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