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

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.

主站蜘蛛池模板: 周口市| 重庆市| 江西省| 凤台县| 曲水县| 杭州市| 鲁山县| 鲜城| 衡水市| 远安县| 平塘县| 吉首市| 漳州市| 承德市| 达拉特旗| 敖汉旗| 田东县| 隆化县| 邵东县| 闵行区| 淳化县| 淅川县| 察哈| 淮滨县| 新竹县| 花莲县| 临高县| 遵义县| 榆林市| 德令哈市| 渝北区| 蒙阴县| 东丰县| 隆化县| 汝州市| 广宗县| 钟祥市| 巴彦淖尔市| 乐安县| 奈曼旗| 娄底市|