C Examples

C Program - Find LCM of Two Numbers without GCD



LCM stands for Least Common Multiple. The LCM of two numbers is the smallest number that can be divided by both numbers.

For example - LCM of 20 and 25 is 100 and LCM of 30 and 40 is 120.

The approach is to start with the largest of the two numbers and keep incrementing the larger number by itself till it becomes divisible by the smaller number.

Example: find LCM of two numbers without GCD

In the example below, to calculate the LCM of two numbers, largest of the two numbers is increased by itself till it becomes divisible by the smaller number.

#include <stdio.h>

int lcm(int x, int y) {
  int i, temp, large, small;
  if (x > y) {
    temp = x;
    x = y;
    y = temp;
  } 
  
  large = y; 
  small = x; 
  i = large;

  while (1) {
    if(i % small == 0)
      return i;
    i = i + large;    
  }  
}

int main() { 
  int x = 30;
  int y = 40;

  printf("LCM of %i and %i is: %i",x,y,lcm(x,y));
  return 0;
}

The above code will give the following output:

LCM of 30 and 40 is: 120