I'm writing a mixed numeral class and need a quick and easy 'greatest common divisor' function. Can anyone give me the code or a link to the code?
I'm tempted to vote to close -- it seems difficult to believe that an implementation would be hard to find, but who knows for sure.
template <typename Number>
Number GCD(Number u, Number v) {
while (v != 0) {
Number r = u % v;
u = v;
v = r;
}
return u;
}
In C++ 17 or newer, you can just #include <numeric>
, and use std::gcd
(and if you care about the gcd, chances are pretty fair that you'll be interested in the std::lcm
that was added as well).