Q:

C++ program to find LCM of two numbers

belongs to collection: C++ programs on various topics

0

C++ program to find LCM of two numbers

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ program Input list of candidates and find winn... >>
<< C++ program to multiply two numbers without using ...