
Problem Statement: Find the LCM of the two given integers.
Examples:
Example 1: Input: n1 = 4, n2 = 8 Output: 8 Explanation: The LCM of 4 and 8 is 8 Example 2: Input: n1 = 5, n2 = 3 Output: 15 Explanation: The LCM of 5 and 3 is 15
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
What is LCM of two numbers?
LCM stands for Least Common Multiple. That is, the lowest multiple of both numbers which is also a common multiple for both of them.
For Example: Can you guess the LCM for (10, 15).
If you have guessed 5, it is incorrect!
Why?
Because 5 is not a multiple of 10 and 15, it is a factor of both of them.
The correct answer will be 30.
How?
Multiples of 10: 10, 20, 30, 40, 50,..... Multiples of 15: 15, 30, 45, 60, 75,..... Now, can you see it is clear that the lowest number common in both of the lists above is 30.
Solution:
- Let n1 and n2 be the two given integers.
- At first, we will find the maximum of n1 and n2
- Then we will check if the max of n1 and n2 is divisible by both n1 and n2 or not.
- If it is not divisible we will keep incrementing max by 1 and in each step, we will check if it is divisible or not.
- When the max is divisible by both n1 and n2 we print that value as LCM.
Code:
C Program
#include <stdio.h>
int main() {
int n1=4, n2=8;
int max;
if(n1>n2)
max=n1;
else
max=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: The LCM of 4 and 8 is 8
Special thanks to Subhrajit Das for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article