- 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.
推薦閱讀
- C++面向?qū)ο蟪绦蛟O(shè)計(第三版)
- Java Web基礎(chǔ)與實(shí)例教程(第2版·微課版)
- ASP.NET Core 2 and Vue.js
- INSTANT Weka How-to
- Python自然語言處理(微課版)
- Xamarin.Forms Projects
- Instant Ext.NET Application Development
- Julia高性能科學(xué)計算(第2版)
- Learning Concurrency in Kotlin
- Babylon.js Essentials
- Access 2010中文版項目教程
- Delphi開發(fā)典型模塊大全(修訂版)
- Software-Defined Networking with OpenFlow(Second Edition)
- Clojure Data Structures and Algorithms Cookbook
- Visual C++程序設(shè)計全程指南