The post on C program calculates the GCD and LCM of two integer numbers.
GCD(Greatest Common Divisor) or HCF: Largest Integer that can divide both the numbers without any remainder or with 0 as remainder. For example, the GCD or HCF of 36 and 48 is 12.
LCM(Least Common Multiple): The LCM of two integers is the smallest positive integer that is perfectly divisible by both the numbers (without a remainder). For example, the LCM of 16 and 24 is 48.
C Program to find HCF and LCM of two Integer Number
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <stdio.h> int main() { int num1, num2, hcf, lcm, count = 1, small; printf("Enter 2 Numbers: \n"); scanf("%d %d", &num1, &num2); small = (num1 < num2) ? num1 : num2; while (count <= small) { if (num1 % count == 0 && num2 % count == 0) { hcf = count; } count++; } lcm = (num1 *num2) / hcf; printf("GCD is: %d\n", hcf); printf("Lcm is: %d", lcm); return 0; } |
Output:
Enter 2 Numbers:
36
48
GCD is: 12
LCM is: 144
C Program to find HCF and LCM using Recursion
Learn more on recursion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <stdio.h> int gcdFunction(int, int); int main() { int num1, num2, hcf, lcm; printf("Enter 2 number: \n"); scanf("%d %d", &num1, &num2); hcf = gcdFunction(num1, num2); lcm = (num1 *num2) / hcf; printf("GCD of %d and %d: %d\n", num1, num2, hcf); printf("LCM of %d and %d: %d\n", num1, num2, lcm); return 0; } int gcdFunction(int x, int y) { if (y == 0) return x; else return gcdFunction(y, x % y); //recursion } |
Output:
Enter 2 number:
36
48
GCD of 36 and 48: 12
LCM of 36 and 48: 144