Find GCD and LCM Using C Program

GCD: The greatest common divisor (GCD), which is also known as the greatest common factor (GCF), of two or more integers, is the largest integer that is a common divisor (factor) of all the given integers.

LCM: The least common multiple (LCM), which is also known as the least common denominator (LCD) in fractions, of two or more integers is the smallest integer that is a common multiple (denominator) of all the given integers.

C program to find GCD & LCM

 #include<stdio.h>

int main()
{
int a, b, x, y, tmp, lcm, gcd;

printf("Enter two integers\n");
scanf("%d%d", &x, &y);

a = x; //Assign value of x to a for farther use.
b = y; //Assign value of y to b for farther use.

while (b != 0)
{
tmp = b;
b = a % b;
a = tmp;
}

gcd = a;
lcm = (x*y)/gcd;

printf("Greatest common divisor of %d and %d is = %d\n", x, y, gcd);
printf("Least common multiple of %d and %d is = %d\n", x, y, lcm);

return 0;
}

 

C program to find LCM and HCF of two numbers using recursion

/*
* C Program to find GCD and LCM of two numbers using recursion
*/
#include <stdio.h>
#include <conio.h> 

int getGcd(int a, int b);
int main(){
 int num1, num2, gcd, lcm;
 textcolor(BLUE+BLINK);
 cprintf("Enter two numbers\n");
 cscanf("%d %d", &num1, &num2);
 /*
 * GCD(a, b) * LCM(a, b) = a*b 
 */
 gcd = getGcd(num1, num2);
 lcm = (num1 * num2)/ gcd;
 textcolor(RED);
 cprintf("GCD of %d and %d is %d\n", num1, num2, gcd);
 cprintf("LCM of %d and %d is %d\n", num1, num2, lcm);
 getch();
 return 0;
}
/*
 * Function to calculate Greatest Common Divisor of two number
 */
 int getGcd(int a, int b) {
 if (b == 0) {
 return a;
 }
 else {
 return getGcd(b, a % b);
 }
}



 Output

GCD LCM

 

 

The following two tabs change content below.

Subroto Mondal

Chief Coordinator HR&CR
I like Programming and New Technologies. And work with Linux.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.