要理解此示例,您应该了解以下 C++ 编程主题:
两个整数a和b的 LCM 是可被a和b整除的最小正整数。
#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(包含 LCM) 打印并终止循环。
如果不是,则将max的值加 1,然后继续相同的过程,直到max被n1和n2整除。
两个数字的 LCM 由下式给出:
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;
}