Find highest common factor and least common multiple using C

HCF stands for Highest Common Factor and LCM is for Least Common Multiple. Here in this article we will make C program to find HCF and LCM. HCF is also known as GCD (Greatest Common Divisor) and GCF (Greatest Common Factor). There are many application in computer science which use the highest common factor or least common multiple.

Now, let’s see some program to find highest common factor and least common multiple in C.

C program to find highest common factor and least common multiple (HCF and LCM)

// C program to find greatest common factor and least common multiple
#include <stdio.h>
int main(){
  int x, y, fNum, sNum, p, hcf, lcm;
  printf("Enter first integer : ");
  scanf("%d", &fNum);
  printf("Enter second integer : ");
  scanf("%d", &sNum);

  x = fNum;
  y = sNum;

  while (y != 0){
    p = y;
    y = x % y;
    x = p;
  }
  hcf = x;
  lcm = (fNum*sNum)/hcf;

  printf("\nGreatest common factor of %d and %d is = %d\n", fNum, sNum, hcf);
  printf("Least common multiple of %d and %d is = %d\n", fNum, sNum, lcm);
  return 0;
}

HCF & LCF program output:

hcf and lcm program in C, highest common factor program in c

C program to find GCD and LCM using function

// C program to find greatest common divisor and least common multiple using function
#include <stdio.h>

long gcdFunction(long i, long j){   // Function definition
  if (i == 0){
    return j;
  }

  while (j != 0){
    if (i > j){
      i = i - j;
    }else{
      j = j - i;
    }
  }
  return i;
}

int main(){
  long a, b, hcf, lcm;

  printf("Enter first integer here : ");
  scanf("%ld", &a);
  printf("Enter second integer here : ");
  scanf("%ld", &b);

  hcf = gcdFunction(a, b);
  lcm = (a * b) / hcf;

  printf("\nGCD of %ld and %ld is = %ld\n", a, b, hcf);
  printf("LCM of %ld and %ld = %ld\n", a, b, lcm);

  return 0;
}

Output of GCD & LCF program

gcd and lcm program in c, hcf and lcm, least common multiple program in c

Previous pageMatrix multiplication

Next pagenCr and nPr in C