最低公共多重程序

Lowest Common Multiple Program

本文关键字:程序      更新时间:2023-10-16

我尝试制作一个程序来查找任意两个数字的最低公倍数。我已经完成了大部分工作,但我的程序打印了 1-1000000 的所有常见倍数,而不仅仅是第一个。如何让它只打印第一个?

#include <iostream>
using namespace std;
int main() {
    cout << "Find the lowest common multiple of two numbers, just enter them one after the other" << endl;
    int firstNum;
    int secondNum;
    cin >> firstNum;
    cin >> secondNum;
    int i;
    for (i = 1; i < 1000001; i++) {
        if (i % firstNum == 0 && i % secondNum == 0) {
            cout << "these two number's LCM is" << i << endl;
        }
    }

    system("pause");
    return 0;
}

您可以添加break来结束循环。在您的情况下,您希望将其添加到 if 语句的末尾:

for (i = 1; i < 1000001; i++) {
    if (i % firstNum == 0 && i % secondNum == 0) {
        cout << "these two number's LCM is" << i << endl;
        break;
    }
}

正如其他人提到的,您的问题是一个break陈述。

但更好的解决方案是:lcm在 C++17 中标准化!所以你可以做:

cout << lcm(firstNum, secondNum) << endl;

如果您无法访问 C++17,这已经在 namespace experimental 中可用:http://en.cppreference.com/w/cpp/experimental/lcm

找到第一个后,您需要从 for 循环中离开,这就是它不断打印其他值的原因。

for (i = 1; i < 1000001; i++) {
if (i % firstNum == 0 && i % secondNum == 0) {
    cout << "these two number's LCM is" << i << endl;
    break;
}

}