# Find LCM of two numbers

Mathematical ProblemsData StructureAlgorithms

In mathematics Least Common Multiple (LCM) is the smallest possible integer, that is divisible by both numbers.

LCM can be calculated by many methods, like factorization, etc. but in this algorithm, we have multiplied the bigger number with 1, 2, 3…. n until we find a number which is divisible by the second number.

## Input and Output

Input:
Two numbers: 6 and 9
Output:
The LCM is: 18

## Algorithm

LCMofTwo(a, b)

Input: Two numbers a and b, considered a > b.

Output: LCM of a and b.

Begin
lcm := a
i := 2
while lcm mod b ≠ 0, do
lcm := a * i
i := i + 1
done

return lcm
End

## Example

#include<iostream>
using namespace std;

int findLCM(int a, int b) {    //assume a is greater than b
int lcm = a, i = 2;

while(lcm % b != 0) {    //try to find number which is multiple of b
lcm = a*i;
i++;
}
return lcm;    //the lcm of a and b
}

int lcmOfTwo(int a, int b) {
int lcm;
if(a>b)    //to send as first argument is greater than second
lcm = findLCM(a,b);
else
lcm = findLCM(b,a);
return lcm;
}

int main() {
int a, b;
cout << "Enter Two numbers to find LCM: "; cin >> a >> b;
cout << "The LCM is: " << lcmOfTwo(a,b);
}

## Output

Enter Two numbers to find LCM: 6 9
The LCM is: 18
Published on 12-Jul-2018 06:13:27