C program to find LCM of any two numbers

Write a C program to enter two numbers and find LCM (Lowest Common Multiple) using for loop. How to find LCM of two given numbers in C programming. Logic to find LCM of two number in C program.

Example

Input

Input number1: 12
Input number2: 30

Output

LCM = 60

Required knowledge

Basic C programming, If else, Conditional operator, For loop

Read more - Program to check divisibility

What is LCM (Lowest Common Multiple)?

LCM is the smallest positive integer that exactly divides two or more numbers. For Example

LCM (Least Common Multiple)

Logic to find LCM of two numbers

To make things simple and generic, I have divided the logic in four steps. Below is the descriptive logic to find LCM.

  1. Find maximum between two numbers. Say max contains maximum between two numbers to find lcm. Maximum is used to generate next multiple which must be common to both.
  2. If max is exactly divisible by both numbers. Then you got your answer, lcm of two numbers is max.
  3. If you did not got your answer in previous step. Then generate next multiple of max.
  4. Repeat 2-3 step till lcm is not found.

Program to find LCM of two numbers

/**
 * C program to find LCM of any two numbers
 */

#include <stdio.h>

int main()
{
    int i, num1, num2, max, lcm=1;

    /*
     * Input two numbers from user
     */
    printf("Enter any two numbers to find LCM: ");
    scanf("%d%d", &num1, &num2);

    // Find maximum between num1 and num2
    max = (num1 > num2) ? num1 : num2;

    // First multiple to be checked for common
    i = max;
    
    // Loop runs forever till lcm is not found
    while(1)
    {
        if(i%num1==0 && i%num2==0)
        {
            /*
             * If i divides both num1 and num2
             * then lcm is found hence exit from loop
             */
            lcm = i;
            break;
        }

        /*
         * If lcm is not found then generate next 
         * multiple of max between both numbers
         */
        i += max;
    }

    printf("LCM of %d and %d = %d", num1, num2, lcm);

    return 0;
}

Note: Do not confuse with the statement max = (num1 > num2) ? num1 : num2;. It finds maximum between two numbers.

Must know - Program to find maximum using conditional operator.

Before you move to next exercise or program. I strongly recommend you to learn the program using recursive approach.

Read more - Program to find LCM using recursion.

Output

Enter any two numbers to find LCM: 12
30
LCM of 12 and 30 = 60

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>