Program to Find LCM of Two Numbers in C

LCM of Two Numbers:

We will write a program to find LCM of two numbers in C language.LCM of two numbers can be defines as the least common multiple or smallest common multiple which can be completely divided by the both numbers. This will help to understand the basic structure and elements of C programming like for or while loop,  if-else, etc.
Program To Find LCM in C

C Program To Find LCM of Two Numbers

LCM(least common multiple) of two numbers means smallest number which is divisbke by both the numbers completely.

For Example:

Algorithm:

  • Step 1: START
  • Step 2: Initialize two variables for num1 and num2.
  • Step 3: Find and store the maximum of num1 and num2 to a separate variable, ‘max’.
  • Step 4: If max is divisible by num1and num2, max is the LCM, hence print it.
  • Step 5: If not divisible, then increment max by 1, and go to step 3 until a number has been printed.
  • Step 6: STOP

Problem 1:LCM Using GCD

lcm * gcd = a * b;
lcm = (a * b) / gcd;
Run
#include<stdio.h> 
int main()
{
    int a=30, b=45, i, gcd, lcm;
    for (i = 1; i <= a && i <= b; ++i) {
        if (a % i == 0 && b % i == 0)
            gcd = i;
    }
    lcm = (a * b) / gcd;
    printf("The LCM of two numbers %d and %d is %d.", a, b, lcm);
    return 0;
}

Output

The LCM of 30 and 45 is 90.

Problem 2:

Run
#include <stdio.h>
int main ()
{
  int a = 30, b = 45, max;
  max = (a > b) ? a : b;
  while (1)
    {
      if ((max % a == 0) && (max % b == 0))
	{
	  printf ("The LCM of %d and %d is %d.", a, b, max);
	  break;
	}
      ++max;
    }
  return 0;
}

Output

The LCM of 30 and 45 is 90.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription