C++ algorithm to calculate least common multiple f

2019-01-23 11:49发布

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条回答
我命由我不由天
2楼-- · 2019-01-23 12:36

You can calculate LCM and or GCM in boost like this:

#include <boost/math/common_factor.hpp>
#include <algorithm>
#include <iterator>


int main()
{
    using std::cout;
    using std::endl;

    cout << "The GCD and LCM of 6 and 15 are "
     << boost::math::gcd(6, 15) << " and "
     << boost::math::lcm(6, 15) << ", respectively."
     << endl;

    cout << "The GCD and LCM of 8 and 9 are "
     << boost::math::static_gcd<8, 9>::value
     << " and "
     << boost::math::static_lcm<8, 9>::value
     << ", respectively." << endl;
}

(Example taken from http://www.boost.org/doc/libs/1_31_0/libs/math/doc/common_factor.html)

查看更多
Animai°情兽
3楼-- · 2019-01-23 12:39

boost provides functions for calculation lcm of 2 numbers (see here)

Then using the fact that

lcm(a,b,c) = lcm(lcm(a,b),c)

You can easily calculate lcm for multiple numbers as well

查看更多
地球回转人心会变
4楼-- · 2019-01-23 12:44

As of C++17, you can use std::lcm.

And here is a little program that shows how to specialize it for multiple parameters

#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;
}

Test it here: https://wandbox.org/permlink/25jVinGytpvPaS4v

查看更多
登录 后发表回答