C Program to calculate hcf and lcm of two number
Objective
Write a C program to calculate the HCF (GCD) and LCM of two numbers.
Algorithm / Approach
- Read two numbers
aandb. - Determine which is the greater (
gr) and which is the lower (low). - Use a
while(low != 0)loop to implement the Euclidean algorithm. - Inside the loop:
temp = gr % low, thengr = low, thenlow = temp. - When the loop finishes,
grholds the HCF. - Calculate the LCM using the formula:
LCM = (a * b) / HCF.
main.c
#include<stdio.h>
int main( ) {
int a,b,temp,gr,low, lcm;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
gr = (a >= b)?a:b;
low = (a < b)?a:b;
while(low!=0) {
temp = gr % low;
gr = low;
low = temp;
}
printf("HCF = %d\n",gr);
lcm = a*b/gr;
printf("LCM = %d\n",lcm);
return 0;
}
Expected Output
Enter two number : 30 40 HCF = 10 LCM = 120
Explanation of the Program
- The Highest Common Factor (HCF) is the largest number that perfectly divides both numbers.
- The Euclidean Algorithm is a highly efficient ancient mathematical method to find the HCF by repeatedly taking the remainder of the larger number divided by the smaller number until the remainder is 0.
- The Least Common Multiple (LCM) is mathematically related to the HCF. The product of two numbers is always equal to the product of their HCF and LCM.
Complexity
Time Complexity
O(log(min(a,b))) - Time complexity of the Euclidean algorithm.
Space Complexity
O(1)