Lets write a C program to find GCD(Greatest Common Divisor) or HCF(Highest common Factor) and LCM(Least Common Multiple) of 2 user entered integer numbers.
Related Read:
while loop in C programming
Relational Operators In C
Logical Operators In C
GCD or HCF: Largest Integer that can divide both the numbers without any remainder or with 0 as remainder.
C Program to Find GCD or HCF of Two Numbers
Least Common Multiple(LCM): is the smallest positive integer that is perfectly divisible by the given integer values.
C Program to Find LCM of Two Numbers
Biggest of Two Numbers Using Ternary Operator: C
Page Contents
Logic To Find GCD and LCM of Two Integer Numbers.
We ask the user to enter 2 integer numbers. Next we find the smallest number among the two. Example, if num1 = 2 and num2 = 3. We can’t have any number bigger than 2, which will divide num1 and have reminder as 0.
Further explanation to find GCD or HCF is present in detail in this article: C Program to Find GCD or HCF of Two Numbers
Formula To Calculate LCM
Once we get the GCD, we use the below formula to calculate LCM.
LCM = ( num1 * num2 ) / GCD;
Source Code: C Program To Find GCD and LCM of Two Numbers
- #include < stdio.h >
- int main()
- {
- int num1, num2, gcd, lcm, count = 1, small;
- printf("Enter 2 integer numbers\n");
- scanf("%d%d", &num1, &num2);
- small = (num1 < num2) ? num1 : num2;
- while(count <= small)
- {
- if(num1 % count == 0 && num2 % count == 0)
- {
- gcd = count;
- }
- count++;
- }
- lcm = ( num1 * num2 ) / gcd;
- printf("GCD = %d\nLCM = %d\n", gcd, lcm);
- return 0;
- }
Output 1:
Enter 2 integer numbers
30
40
GCD = 10
LCM = 120
Output 2:
Enter 2 integer numbers
12
24
GCD = 12
LCM = 24
C Program To Find GCD and LCM of Two Numbers
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert