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

  • The Modern C++ Challenge
  • Marius Bancila
  • 174字
  • 2021-06-25 22:01:23

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.

主站蜘蛛池模板: 沅江市| 莎车县| 罗山县| 高邮市| 蓬溪县| 贞丰县| 中江县| 洛隆县| 定结县| 巴南区| 望谟县| 明星| 阿拉尔市| 苗栗县| 汉寿县| 石家庄市| 禄劝| 固镇县| 翼城县| 泽库县| 武宁县| 昌吉市| 建湖县| 南投县| 福建省| 延安市| 灵川县| 彩票| 和林格尔县| 从江县| 曲阳县| 呼伦贝尔市| 石台县| 沭阳县| 泸州市| 台前县| 六盘水市| 清河县| 安阳县| 乐陵市| 德钦县|