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

Ask*_*ner 25 c++ algorithm lcm

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

Bla*_*ace 46

您可以使用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';
}
Run Code Online (Sandbox Code Playgroud)

  • @FerencDajka:`for(;;){}`是一个非常常见的无限循环的C和C++习语.我使用它部分是出于习惯,因为有些编译器会对`while(true){}`发出警告.[见相关问题](http://stackoverflow.com/questions/20186809/endless-loop-in-cc) (4认同)
  • 稍微优化:`int result = std :: accumulate(arr + 1,arr + 4,arr [0],lcm);` (2认同)

Vla*_*mir 17

boost提供计算lcm的2个数字的函数(见这里)

然后使用这个事实

lcm(a,b,c) = lcm(lcm(a,b),c)
Run Code Online (Sandbox Code Playgroud)

您也可以轻松计算多个数字的lcm


Ste*_*314 6

该算法不是特定于C++的.AFAIK,没有标准的库函数.

要计算最小公倍数,首先使用欧几里德算法计算GCD(最大公约数).

http://en.wikipedia.org/wiki/Greatest_common_divisor

GCD算法通常给出两个参数,但......

GCD (a, b, c) = GCD (a, GCD (b, c))
              = GCD (b, GCD (a, c))
              = GCD (c, GCD (a, b))
              = ...
Run Code Online (Sandbox Code Playgroud)

要计算LCM,请使用......

                a * b
LCM (a, b) = ----------
             GCD (a, b)
Run Code Online (Sandbox Code Playgroud)

其逻辑基于素数因子分解.更一般的形式(超过两个变量)是......

                                          a                 b        
LCM (a, b, ...) = GCD (a, b, ...) * --------------- * --------------- * ...
                                    GCD (a, b, ...)   GCD (a, b, ...)
Run Code Online (Sandbox Code Playgroud)

编辑 - 实际上,我认为最后一点可能是错误的.但是,第一个LCM(两个参数)是正确的.


sma*_*c89 6

从 C++17 开始,您可以使用std::lcm.

这是一个小程序,展示了如何将它专门用于多个参数

#include <numeric>
#include <iostream>

namespace math {

    template <typename M, typename N>
    constexpr auto lcm(const M& m, const N& n) {
        return std::lcm(m, n);
    }

    template <typename M, typename ...Rest>
    constexpr auto lcm(const M& first, const Rest&... rest) {
        return std::lcm(first, lcm(rest...));
    }
}

auto main() -> int {
    std::cout << math::lcm(3, 6, 12, 36) << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在这里查看它的实际效果:https : //wandbox.org/permlink/25jVinGytpvPaS4v


小智 5

使用 GCC 和 C++14 以下代码对我有用:

#include <algorithm>
#include <vector>

std::vector<int> v{4, 6, 10};    
auto lcm = std::accumulate(v.begin(), v.end(), 1, [](auto & a, auto & b) {
    return abs(a * b) / std::__gcd(a, b);
});
Run Code Online (Sandbox Code Playgroud)

在 C++17 中有 std::lcm 函数(http://en.cppreference.com/w/cpp/numeric/lcm)可以直接用于累加。


Joh*_*ing 1

未内置于标准库中。您需要自己构建它,或者获得一个可以完成它的库。我敢打赌 Boost 有一个...