To Find HCF LCM in C


Q. Write a C program to find HCF(GCD) and LCM ?

#include <stdio.h>
#include <conio.h>

void main() {
    int a, b, i, j, t, gcd, lcm;
    printf("Enter two integers\n");
    scanf("%d %d", &a, &b);
    i = a;
    j = b;
    while (j > 0) 
    {
        t = j;
        j = i % j;
        i = t;
    }
    gcd = i;
    lcm = (a*b)/gcd;
    printf("Greatest common divisor(GCD or HCF) of %d and %d is %d\n",a,b,gcd);
    printf("Least common multiple of %d and %d is %d\n",a,b,lcm);
    getch();
}

Q. Write an algorithm to find HCF(GCD) and LCM ?

1. Start
2. Read inputs:
    - Prompt the user to enter two integers `a` and `b`.
    - Read the two values.
3. Initialize variables:
    - Set `i = a`
    - Set `j = b`
4. Compute GCD using the Euclidean algorithm:
    - While `j > 0` do:
    - Store the value of `j` in a temporary variable `t`.
    - Update `j` as `i` modulo `j` (`j = i % j`).
    - Update `i` with the value stored in `t`.
    - When the loop ends, `i` contains the GCD.
5. Calculate LCM:
    - Use the relationship:
      \[
      \text{LCM} = \frac{a \times b}{\text{GCD}}
      \]
6. Display results:
    - Print the GCD of `a` and `b`.
    - Print the LCM of `a` and `b`.
7. End
 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.