C Program to Calculate HCF and LCM of two Number
Objective
Write a C program to calculate HCF and LCM using functions.
Algorithm / Approach
- Create a function
hcf(a, b)that uses a loop to find the remainder of a division and swap variables until the remainder is 0. - Create a function
lcm(a, b)that calculates(a * b) / hcf(a, b). - Call these from
main()and print the results.
main.c
#include<stdio.h>
int lcm(int , int);
int hcf(int , int);
int main( ) {
int a,b;
printf("Enter two Number : ");
scanf("%d%d",&a,&b);
int lc=lcm(a,b);
int hc =(a>b)?hcf(a,b):hcf(b,a);
printf("LCM = %d\n",lc);
printf("HCF = %d\n",hc);
return 0;
}
int lcm(int a, int b) {
int res = a*b/hcf(a,b);
return res;
}
int hcf(int a, int b) {
int rem;
while( low != 0) {
rem = a%b;
a = b;
b = rem;
}
return gre;
}
Expected Output
Enter two Number : 15 50 LCM = 150 HCF = 5
Explanation of the Program
- Functions can call other functions! In this program,
main()callslcm(), andlcm()internally callshcf()to complete its mathematical formula. - Note: The provided code contains undefined variables in the
hcffunction (lowandgre). This is a common bug when refactoring procedural code into functions and forgetting to move the variable declarations.
Complexity
Time Complexity
O(log(min(a,b)))
Space Complexity
O(1)
Common Mistakes
- Failing to declare variables used inside a function. In the snippet provided,
lowandgreare used in thehcffunction but were never declared, which will cause a compilation error.