C++ 编程:寻找最小公倍数
为了理解这个示例,你应该具备以下 C++ 编程 主题的知识:
两个整数 a
和 b
的最小公倍数(LCM)是能够同时被 a
和 b
整除的最小正整数。
示例 1:查找 LCM
#include <iostream>
using namespace std;
int main()
{
int n1, n2, max;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
// 将 n1 和 n2 之间的最大值存储在 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
整除,如果它可以被这两个数整除,就打印出包含 LCM 的 max
并终止循环。
如果不是,max
的值增加 1,并重复同样的过程,直到 max
可以被 n1
和 n2
都整除。
示例 2:使用 HCF 查找 LCM
两个数的 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;
}