In this article, we are going to learn about a simple C program, to find the LCM of two given numbers. The program is very simple, provided that you already know how to calculate the LCM of given numbers, and you know some basics of C programming.
Let’s understand what is LCM first, and then we will quickly move to the program explanation.
C program to find LCM of Two Numbers
LCM means Lowest common multiple, so when we are having 2 numbers, and we need to calculate the LCM of those two numbers, it simply means that we need to find such a number, which is a multiple of both the given numbers, and it is the lowest of all the multiples.
In other words, the LCM of two numbers n1 and n2 is the lowest positive integer, which is perfectly divisible by both n1 and n2. For example, LCM of 12 and 18 is 36, because it is the smallest common multiple for both the given numbers.
In the given video, you can find a detailed explanation and program for LCM of two numbers, in C language.
Here is the C program to calculate the LCM of two given numbers –
#include <stdio.h>
int main() {
int num1, num2, max, lcm;
// Prompt the user to enter two numbers
printf(“Enter two positive integers: “);
scanf(“%d %d”, &num1, &num2);
// Finding the maximum of the two numbers
max = (num1 > num2) ? num1 : num2;
while (1) {
if (max % num1 == 0 && max % num2 == 0) {
lcm = max;
break;
}
++max;
}
// Display the LCM
printf(“The LCM of %d and %d is %dn”, num1, num2, lcm);
return 0;
}
Program Output 1 –
Enter two positive integers: 12 18
The LCM of 12 and 18 is 36
Program Output 2 –
Enter two positive integers: 2 6
The LCM of 2 and 6 is 6