C

Finding The LCM Of Two Numbers In C

This tutorial will teach you how to write a C program to find the LCM of two numbers.

What exactly is LCM?

LCM is an abbreviation for lowest common multiple. The LCM of two integers num1 and num2 is the smallest positive integer that is perfectly divisible by both numbers, with a remainder of zero. The LCM of 15 and 50, for example, is 150 because 150 is the smallest number that is perfectly divisible by both 15 and 50.

Exemplification 1: Using a while loop, create a program to find the LCM of two numbers.

In this example, the program asks the user to enter two integers. The positive integers entered are stored in num1 and num2 using the scanf() function.
The greater of these two numbers is saved in another variable called max. The LCM can never be less than the maximum value. Now we’re running a while loop, incrementing the value of max by one and checking whether the max is perfectly divisible by both numbers on each iteration. If so, display the maximum value as the LCM of these two numbers; otherwise, increase the maximum value and check again.

#include <stdio.h>
int main() {
  int num1, num2, max;
  printf("Enter two positive integers: ");
  scanf("%d %d", &num1, &num2);

  // greater number between num1 and num2 is stored in max
  max = (num1 > num2) ? num1 : num2;

  while (1) {
    if (max % num1 == 0 && max % num2 == 0) {
      printf("LCM of input numbers %d and %d is %d.", num1, num2, max);
      break;
    }
    ++max;
  }
  return 0;
}

Example 2: Write a program to compute the LCM from the GCD of two numbers.

Another method for calculating the LCM of two numbers is to use the formula LCM = (num1*num2)/GCD. In this example, we find the GCD of two input numbers and then use the mentioned mathematical formula to calculate the LCM.

#include <stdio.h>
int main() {
  int num1, num2, i, gcd, lcm;
  printf("Enter two positive integers: ");
  //storing user input into num1 and num2
  scanf("%d %d", &num1, &num2);

  for (i = 1; i <= num1 && i <= num2; ++i) {

    // check if the current value of i is a
    // factor of both integers num1 and num2
    if (num1 % i == 0 && num2 % i == 0)
      gcd = i;
  }

  //Mathematical formula to calculate LCM from GCD
  lcm = (num1 * num2) / gcd;

  printf("LCM of two input numbers %d and %d is: %d.", num1, num2, lcm);
  return 0;
}

Related Articles

Leave a Reply

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

Back to top button