lcm c++
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.
两个给定数字 m和n的 LCM(最小公倍数)通过找到可被两个数字整除的最小数字来确定。 解决此问题的一种简单方法是将a和b的最大值存储在变量max中,并检查max是否可完全被两个数整除,如果是,则max为lcm,否则将max递增1。
C ++程序使用简单方法查找LCM (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
使用GCD查找LCM的C ++程序 (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和HCF的属性,我们知道两个数的乘积等于LCM和HCF的乘积。
因此,两个数字的LCM由下式给出: LCM = (n1 * n2) / HCF
We know that, HCF (highest common factor) = GCD (greatest common divisor)
我们知道,HCF(最高公因数)= GCD(最大公因数)
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
翻译自: https://www.includehelp.com/cpp-programs/find-lcm-of-two-numbers.aspx
lcm c++