May 2018
Intermediate to advanced
328 pages
8h 15m
English
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 divisible by all of them. A possible way to compute the least common multiple is by reducing the problem to computing the greatest common divisor. 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 ...
Read now
Unlock full access