- 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.
推薦閱讀
- JavaScript+DHTML語法與范例詳解詞典
- 微服務與事件驅動架構
- Learning SAP Analytics Cloud
- Learning Network Forensics
- ExtJS高級程序設計
- HTML5從入門到精通(第4版)
- C++寶典
- Getting Started with Python and Raspberry Pi
- Elasticsearch Essentials
- Nagios Core Administration Cookbook(Second Edition)
- Scala編程實戰
- Unity 2017 Game AI Programming(Third Edition)
- Mastering HTML5 Forms
- Go語言入門經典
- After Effects CC案例設計與經典插件(視頻教學版)