官术网_书友最值得收藏!

3. Least common multiple

The least common multiple (lcm) of two or more non-zero integers, also known as the lowest common multiple, or smallest common multiple, is the smallest positive integer that is pisible by all of them. A possible way to compute the least common multiple is by reducing the problem to computing the greatest common pisor. The following formula is used in this case:

lcm(a, b) = abs(a, b) / gcd(a, b)

A function to compute the least common multiple may look like this:

int lcm(int const a, int const b)
{
int h = gcd(a, b);
return h ? (a * (b / h)) : 0;
}

To compute the lcm for more than two integers, you could use the std::accumulate algorithm from the header <numeric>:

template<class InputIt>
int lcmr(InputIt first, InputIt last)
{
return std::accumulate(first, last, 1, lcm);
}

In C++17 there is a constexpr function called lcm() in the header <numeric> that computes the least common multiple of two numbers.

主站蜘蛛池模板: 电白县| 潼关县| 巴南区| 涡阳县| 东光县| 安国市| 汝州市| 铜鼓县| 彭泽县| 剑阁县| 长武县| 华宁县| 宣威市| 得荣县| 梁平县| 江西省| 定远县| 曲沃县| 郯城县| 陵川县| 罗城| 镇安县| 股票| 开远市| 龙游县| 奎屯市| 汶川县| 克东县| 临沧市| 海阳市| 西盟| 荣昌县| 宝坻区| 呼伦贝尔市| 鲜城| 无棣县| 翁牛特旗| 若羌县| 达拉特旗| 嘉黎县| 吉木乃县|