To Find LCM of Two Numbers in C

  • The LCM of two numbers a and b is the smallest positive integer that is perfectly divisible by both a and b (without a remainder). For example: The LCM of 72 and 120 is 360.

Sample Code

#include <stdio.h> 
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
// Everything divides 0
if (a == 0 || b == 0)
return 0;
// Base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// Function to return LCM of two numbers
int lcm(int a, int b)
{
return (a*b)/gcd(a, b);
}
// Driver program to test above function
int main()
{
int a = 10, b = 28;
printf("LCM of %d and %d is %d ", a, b, lcm(a, b));
return 0;
}

Output

LCM of 10 and 28 is 140

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,