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

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.

主站蜘蛛池模板: 北安市| 太仓市| 谷城县| 汉沽区| 太仓市| 化隆| 曲水县| 三台县| 呼图壁县| 五大连池市| 崇义县| 江山市| 和平区| 珠海市| 康平县| 岐山县| 龙口市| 天津市| 长兴县| 积石山| 平邑县| 万荣县| 邻水| 西昌市| 四子王旗| 都匀市| 沙河市| 洪泽县| 桂林市| 自治县| 油尖旺区| 福建省| 石渠县| 县级市| 休宁县| 都昌县| 康定县| 习水县| 德保县| 泗阳县| 四子王旗|