C PROGRAM
Program to find LCM and HCF of two numbers |C Program|
Introduction
Understanding the Least Common Multiple (LCM) and Highest Common Factor (HCF) of two numbers is essential in various mathematical and algorithmic applications. In this blog post, we'll dissect a simple C program that calculates the LCM and HCF of two user-input numbers, providing insights into the underlying logic.
Code
#include<stdio.h>
#include<conio.h>
int lcm(int, int);
int hcf(int, int);
void main() {
int a, b;
clrscr();
printf("Enter the numbers: ");
scanf("%d%d", &a, &b);
printf("\nLeast Common Multiple is %d", lcm(a, b));
printf("\nThe Highest Common Factor is %d", hcf(a, b));
getch();
}
int lcm(int a, int b) {
int n;
for (n = 1;; n++) {
if (n % a == 0 && n % b == 0)
return n;
}
}
int hcf(int a, int b) {
int c;
if (a < b) {
c = a;
a = b;
b = c;
}
while (1) {
c = a % b;
if (c == 0)
return b;
a = b;
b = c;
}
}
Output
// Output
enter the numbers 10 20
least common multiple is 20
highest common factor is 10
Explanation
1. Header Files:
The program includes the standard input/output header <stdio.h> and the console I/O header <conio.h>.
2. Main Function:
The main function initiates the program.
Users are prompted to enter two numbers (a and b) for which the LCM and HCF will be calculated.
The LCM and HCF are calculated using the lcm and hcf functions, respectively.
3. LCM Function:
The lcm function iteratively searches for the smallest number that is divisible by both a and b.
The function returns the calculated LCM.
4. HCF Function:
The hcf function uses the Euclidean algorithm to find the HCF of a and b.
The function returns the calculated HCF.
5. User Interaction:
Users receive the calculated LCM and HCF as output.
Conclusion
This C program provides a basic but functional implementation of finding the Least Common Multiple and Highest Common Factor. While the code achieves its purpose, it's essential to note that there are more efficient algorithms for these calculations, especially for larger numbers.
Experiment with different input values, explore alternative algorithms for LCM and HCF, and consider optimizations to enhance your understanding of these fundamental mathematical concepts. Mastering these skills will be valuable in various algorithmic and mathematical applications. Happy coding!
Post a Comment
0 Comments