Learn how to write a C program to calculate the Least Common Multiple (LCM) of two numbers. This guide explains how to use the relationship between GCD and LCM to compute the LCM efficiently. It includes step-by-step instructions, sample code, and explanations of key concepts. Ideal for beginners who want to understand basic number theory and programming techniques in C.
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
int main() {
int num1, num2;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
printf("LCM of %d and %d is %d.\n", num1, num2, lcm(num1, num2));
return 0;
}
Inside the gcd function:
- Recursive implementation of Euclidean algorithm to find the GCD of two numbers.
Inside the lcm function:
- Calculates the LCM using the formula: (a * b) / gcd(a, b)
Inside the main() function:
- Two integer variables num1 and num2 are declared to store the input numbers.
- The user is prompted to enter two positive integers.
- The lcm function is called with the two numbers as arguments, and the result is printed.