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?
The libstdc++ algorithm library has a hidden gcd function (I'm using g++ 4.6.3).
#include <iostream>
#include <algorithm>
int main()
{
std::cout << std::__gcd(100,24); // print 4
return 0;
}
You are welcome :)
UPDATE: As @chema989 noted it, in C++17 there is std::gcd()
function available with <numeric>
header.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With