C Program to Find HCF (GCD) and LCM Using Recursive Function


Question: Write a program in C to find Highest Common Factor (HCF) ( also known as Greatest Common Divisor (GCD)) and Least Common Multiple (LCM) using Recursive Function.

HCF and LCM Using Recursive Function


#include <stdio.h>

long int hcf(long int, long int);

int main()
{
  long int number1, number2, gcd, lcm;
  printf("Enter two integer numbers:\n");
  scanf("%ld%ld", &number1, &number2);

  gcd = hcf(number1, number2);
  lcm = (number1*number2)/gcd;

  printf("HCF of %ld and %ld = %ld\n", number1, number2, gcd);
  printf("LCM of %ld and %ld = %ld\n", number1, number2, lcm);

  return 0;
}

long int hcf(long int a, long int b) {
  if (b == 0)
  {
    return a;
  }
  else
  {
    return hcf(b, a % b);
  }
}

Output

Enter two integer numbers:
24
36
HCF of 24 and 36 = 12
LCM of 24 and 36 = 72