- 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.
推薦閱讀
- Learning Java Functional Programming
- Android開發精要
- 零基礎玩轉區塊鏈
- Learning ArcGIS Pro 2
- Learning Elixir
- 跟老齊學Python:輕松入門
- Scratch 3游戲與人工智能編程完全自學教程
- Julia Cookbook
- HTML5 and CSS3 Transition,Transformation,and Animation
- Mastering Akka
- Kubernetes源碼剖析
- Mastering JavaScript
- iOS Development with Xamarin Cookbook
- Flutter從0基礎到App上線
- AI輔助編程Python實戰:基于GitHub Copilot和ChatGPT