In the world of computer programming, it is important to understand basic mathematical concepts like the highest common factor(HCF) and least common multiple(LCM) etc. These concepts play an important role in solving various mathematical problems. In this article, we are going to write a C program to compute HCF and LCM of two numbers.
What are LCM and HCF
HCF(Highest Common Factor), also known as the greatest common divisor (GCD) refers to the largest positive integer that can divide two or more integers without leaving a remainder. On the other hand, LCM(Least Common Multiple) is the smallest multiple that is evenly division by two or more numbers.
C Program for LCM and HCF
#include <stdio.h>
int calculateHCF(int num1, int num2)
{
while (num1 != num2)
{
if (num1 > num2)
{
num1 = num1 - num2;
}
else
{
num2 = num2 - num1;
}
}
return num1;
}
int calculateLCM(int num1, int num2)
{
int hcf = calculateHCF(num1, num2);
int lcm = (num1 * num2) / hcf;
return lcm;
}
void main()
{
int num1, num2;
printf("Enter the first number");
scanf("%d", &num1);
printf("Enter the second number");
scanf("%d", &num2);
int hcf = calculateHCF(num1, num2);
int lcm = calculateLCM(num1, num2);
printf("HCF of %d and %d = %d\n", num1, num2, hcf);
printf("LCM of %d and %d = %d", num1, num2, lcm);
}
Output-
How the Above C Program Works?
- The above C program for LCM and HCF starts by prompting the user to input two numbers.
- calculate HCF function implement the logic for calculating the HCF of two numbers.
- calculateLCM function implements the logic for calculating LCM of two numbers.
- Finally, the program prints the LCM and HCF of the given two numbers.
The C program serves as a basic foundation to learn the concept and implement the logic for computing LCM and HCF of two numbers by using C programming language. We can also use other programming languages for computing LCM and HCF.
3 thoughts on “C Program for LCM and HCF”