两个整数 a 和 b 的 最小公倍数 (LCM) 是能同时被 a 和 b 整除的最小正整数。
示例 1:求最小公倍数
#include <iostream>
using namespace std;
int main()
{
int n1, n2, max;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
// maximum value between n1 and n2 is stored in max
max = (n1 > n2) ? n1 : n2;
do
{
if (max % n1 == 0 && max % n2 == 0)
{
cout << "LCM = " << max;
break;
}
else
++max;
} while (true);
return 0;
}
输出
Enter two numbers: 12 18 LCM = 36
在上面的程序中,要求用户输入两个整数 n1 和 n2,并将较大的数存储在 max 中。
检查 max 是否能同时被 n1 和 n2 整除,如果能,则打印 max (其中包含最小公倍数)并终止循环。
如果不能,则 max 的值增加 1,并重复此过程,直到 max 能同时被 n1 和 n2 整除为止。
示例 2:使用 HCF 求最小公倍数
两个数的最小公倍数由下式给出:
LCM = (n1 * n2) / HCF
访问此页面了解: 如何在 C++ 中计算 HCF?
#include <iostream>
using namespace std;
int main()
{
int n1, n2, hcf, temp, lcm;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
hcf = n1;
temp = n2;
while(hcf != temp)
{
if(hcf > temp)
hcf -= temp;
else
temp -= hcf;
}
lcm = (n1 * n2) / hcf;
cout << "LCM = " << lcm;
return 0;
}