LCM 两个整数
a 和
b 是可以被两个整数整除的最小正整数
>a 和
b。
示例 1: 查找 LCM
#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.
示例 2: 使用 HCF 查找 LCM
两个数字的 LCM 由下式给出:
LCM = (n1 * n2) / HCF
访问此页面了解: 如何计算HCF在 C++ 中?
#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; }