C++ 实例 - 求两数最小公倍数

用户输入两个数,其这两个数的最小公倍数。

实例

#include <bits/stdc++.h>
using namespace std;
 
int main() {
    int n1, n2, max;
    // 输入两个数
    cin >> n1 >> n2;
    
    // 获取最大的数
    max = (n1 > n2) ? n1 : n2;

    do {
        if (max % n1 == 0 && max % n2 == 0) {
            cout << "LCM = " << max;
            break;
        } else
            ++max;
    } while (true);
    
    return 0;
}

以上程序执行输出结果为:

12 18
LCM = 36

实例

#include <bits/stdc++.h>
using namespace std;
 
int main() {
    int n1, n2, hcf, temp, lcm;
    // 输入两个数
    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;
}

以上程序执行输出结果为:

78 52
HCF = 156