C PROGRAM ON GCD LCM AND HCF

C Program to Find GCD and LCM of Two Numbers using Euclidean Algorithm

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
int gcd(int x, int y) {
    int r = 0, a, b;
    a = (x > y) ? x : y; // a is greater number
    b = (x < y) ? x : y; // b is smaller number
 
    r = b;
    while (a % b != 0) {
        r = a % b;
        a = b;
        b = r;
    }
    return r;
}
 
int lcm(int x, int y) {
    int a;
    a = (x > y) ? x : y; // a is greater number
    while (1) {
        if (a % x == 0 && a % y == 0)
            return a;
        ++a;
    }
}
 
int main(int argc, char **argv) {
    printf("Enter the two numbers: ");
    int x, y;
    scanf("%d", &x);
    scanf("%d", &y);
    printf("The GCD of two numbers is: %d", gcd(x, y));
    printf("The LCM of two numbers is: %d", lcm(x, y));
    return 0;
}

Output:

$ gcc GCDLCM.c
$ ./a.out
 
Enter the two numbers: 12 15
The GCD of two numbers is: 3
The LCM of two numbers is: 60

C Program to Find HCF of Two Numbers without Recursion

/*
 * C Program to find HCF of a given Number without using Recursion
 */
#include <stdio.h>
 
int hcf(int, int);
 
int main()
{
    int a, b, result;
 
    printf("Enter the two numbers to find their HCF: ");
    scanf("%d%d", &a, &b);
    result = hcf(a, b);
    printf("The HCF of %d and %d is %d.\n", a, b, result);
 
    return 0;
}
 
int hcf(int a, int b)
{
    while (a != b)
    {
        if (a > b)
        {
            a = a - b;
        }
        else
        {
            b = b - a;
        }
    }
    return a;
}
$ cc pgm31.c
$ a.out
Enter the two numbers to find their HCF: 24 36
The HCF of 24 and 36 is 12.