Search code examples
c++algorithmgreatest-common-divisor

What is the difference between std::__gcd and std::gcd?


Many websites and questions on Stack Overflow reference a function named std::__gcd. What’s the difference between this function and std::gcd?


Solution

  • I did some sleuthing on this. It looks like the __gcd function is a private helper function defined in the libstdc++ implementation of the <algorithm> header (line 1503). It’s used internally only by the std::rotate function (line 1610). It was (probably) never intended to be used directly outside of the library implementation. Because it’s specific to libstdc++, trying to use this function through compilers other than g++ isn’t guaranteed to work. In that sense, you can think of the std::__gcd function as a (poorly documented) internal helper that’s only available with some C++ compilers.

    (Fun fact: I was first alerted to the existence of __gcd by a now-deleted question here asking why it handled negative inputs inconsistently. Turns out it wasn’t really designed to handle negative numbers, since the libstdc++ implementation only uses it in cases where the inputs are nonnegative. It’s one of the risks of using an undocumented internal helper function!)

    On the other hand, std::gcd is a standard C++ library function that was introduced in C++17. This means that any C++17-compliant compiler will support std::gcd, so it’s preferable to use this option if you have a C++17-compliant compiler.

    For C++14 or lower, you can simply implement your own version GCD function. Euclid’s algorithm is very straightforward to code up and runs extremely quickly.