# C++ program to find LCM of two numbers

Here, we are going to learn how to **find LCM of two numbers using simple way and LCM using GCD**?

Submitted by Vivek Kothari, on November 17, 2018

**LCM (least common multiple) of two given numbers** m and n is determined by finding the smallest number that is divisible by both the numbers. A simple approach to this problem is to store the maximum of a and b in variable max and check if max is completely divisible by both the numbers, if yes then max is the lcm otherwise increment max by 1.

### C++ program to find LCM using simple approach

#include <iostream> using namespace std; int main() { int m,n,max; m=12; n=15; if(m > n) max= m; else max = n; while(true) { if (max % m == 0 && max % n == 0) { cout << "LCM of "<<m<<" and "<<n<<" = "<< max; break; } else max++; } return 0; }

**Output**

LCM of 12 and 15 = 60

### C++ program to find LCM using GCD

We can also use the property of LCM and HCF, we know that the product of two numbers is equal to the product of LCM and HCF.

Therefore LCM of two numbers is given by:LCM = (n1 * n2) / HCF

We know that, HCF (highest common factor) = GCD (greatest common divisor)

So, LCM = (n1 * n2) / GCD

#include <iostream> using namespace std; //function to return gcd of a and b int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { int m,n; m=12; n=15; cout<<"LCM of "<<m<<" and "<<n<<" = "<<(m*n)/gcd(m,n)<<endl; m=7; n=100; cout<<"LCM of "<<m<<" and "<<n<<" = "<<(m*n)/gcd(m,n); }

**Output**

LCM of 12 and 15 = 60 LCM of 7 and 100 = 700

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.

Learn PCB Designing: PCB DESIGNING TUTORIAL