- 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.
推薦閱讀
- 黑客攻防從入門到精通(實(shí)戰(zhàn)秘笈版)
- Hands-On Data Structures and Algorithms with JavaScript
- R語言游戲數(shù)據(jù)分析與挖掘
- 編寫整潔的Python代碼(第2版)
- Python Deep Learning
- Mastering PHP Design Patterns
- Visual Basic程序設(shè)計實(shí)驗指導(dǎo)(第4版)
- Python面向?qū)ο缶幊蹋簶?gòu)建游戲和GUI
- concrete5 Cookbook
- 微信小程序入門指南
- Learning Concurrent Programming in Scala
- Access 2010數(shù)據(jù)庫應(yīng)用技術(shù)(第2版)
- Natural Language Processing with Java and LingPipe Cookbook
- Java語言程序設(shè)計教程
- JavaScript腳本特效編程給力起飛