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 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 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.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset