C++ algorithm to calculate least common multiple for multiple numbers

后端 未结 15 1936
太阳男子
太阳男子 2020-12-14 16:29

Is there a C++ algorithm to calculate the least common multiple for multiple numbers, like lcm(3,6,12) or lcm(5,7,9,12)?

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 17:18

    I found this while searching a similar problem and wanted to contribute what I came up with for two numbers.

    #include 
    #include 
    using namespace std;
    
    int main()
    {
        cin >> x >> y;
    
        // zero is not a common multiple so error out
        if (x * y == 0)
            return -1;
    
        int n = min(x, y);
        while (max(x, y) % n)
            n--;
    
        cout << n << endl;
    }
    

提交回复
热议问题