C++算法计算多个数字的最小公倍数

标签 c++ algorithm lcm

是否有 C++ 算法来计算多个数字的最小公倍数,例如 lcm(3,6,12)lcm(5,7,9,12)?

最佳答案

您可以使用 std::accumulate 和一些辅助函数:

#include <iostream>
#include <numeric>

int gcd(int a, int b)
{
    for (;;)
    {
        if (a == 0) return b;
        b %= a;
        if (b == 0) return a;
        a %= b;
    }
}

int lcm(int a, int b)
{
    int temp = gcd(a, b);

    return temp ? (a / temp * b) : 0;
}

int main()
{
    int arr[] = { 5, 7, 9, 12 };

    int result = std::accumulate(arr, arr + 4, 1, lcm);

    std::cout << result << '\n';
}

关于C++算法计算多个数字的最小公倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4229870/

相关文章:

c# - 如何使用 C# .net 从命令行调用带有多个参数的 C++ exe

c++ - 快速排序 C++ 中的 Lambda

algorithm - 为什么运行 DFA 需要线性时间?

ios - 如何在 iOS 中创建特定于温度的颜色图表

Java:输入两个错误值后程序崩溃

c++ - boost.build 与 boost.python

c++ - 代码值应该每次都更改,因此不会显示相同的座位,但不会显示

python - 查找 "good"邻居的算法 - 图着色?

frequency - 计算一组数字的近似 LCM

python - 查找多个 datetime.timedelta 对象的最小公倍数