num1
and num2
is the smallest positive integer that is perfectly divisible by both the numbers, perfectly means the remainder is zero. scanf()
function.#include <stdio.h>
int main() {
int num1, num2, max;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
// greater number between num1 and num2 is stored in max
max = (num1 > num2) ? num1 : num2;
while (1) {
if (max % num1 == 0 && max % num2 == 0) {
printf("LCM of input numbers %d and %d is %d.", num1, num2, max);
break;
}
++max;
}
return 0;
}
Enter two positive integers: 15
50
LCM of input numbers 15 and 50 is 150.
LCM = (num1*num2)/GCD
. In this example, we are finding the GCD of two input numbers and then calculating the LCM using the mentioned mathematical formula.#include <stdio.h>
int main() {
int num1, num2, i, gcd, lcm;
printf("Enter two positive integers: ");
//storing user input into num1 and num2
scanf("%d %d", &num1, &num2);
for (i = 1; i <= num1 && i <= num2; ++i) {
// check if the current value of i is a
// factor of both integers num1 and num2
if (num1 % i == 0 && num2 % i == 0)
gcd = i;
}
//Mathematical formula to calculate LCM from GCD
lcm = (num1 * num2) / gcd;
printf("LCM of two input numbers %d and %d is: %d.", num1, num2, lcm);
return 0;
}
Enter two positive integers: 12
38
LCM of two input numbers 12 and 38 is: 228.