C program to find LCM of any two numbers

Previous Program Next Program

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.



Input number1: 12
Input number2: 30


LCM = 60

Required knowledge

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

What is LCM (Lowest Common Multiple)?

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

LCM of two numbers

Logic to find LCM of two numbers

Before I get deep in the logic to find LCM. You must know how to check divisibility of any number.

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;

     * Read 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
        if(i%num1==0 && i%num2==0)
             * If i divides both num1 and num2
             * then lcm is found hence exit from loop
            lcm = i;

         * 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. Read more about finding maximum using conditional operator.

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

Happy coding ;)

Recommended posts

Previous Program Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment