Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to Calculate HCF and LCM of two Number

C Code Example — Function Programs

ADVERTISEMENT

C Program to Calculate HCF and LCM of two Number

Objective

Write a C program to calculate HCF and LCM using functions.

Algorithm / Approach

  1. 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.
  2. Create a function lcm(a, b) that calculates (a * b) / hcf(a, b).
  3. 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() calls lcm(), and lcm() internally calls hcf() to complete its mathematical formula.
  • Note: The provided code contains undefined variables in the hcf function (low and gre). 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, low and gre are used in the hcf function but were never declared, which will cause a compilation error.
ADVERTISEMENT