In Python the Extended Euclidean Algorithm (egcd) could be written as follows:
def egcd(a, b):
if b == 0:
return (a, 1, 0)
else:
(d, tmp, s) = egcd(b, a%b)
return (d, s, tmp - (a//b) * s)
I want to write a native and modern C++ version of the egcd. This is what I have so far:
template<typename A, typename B, typename T = std::common_type_t<A, B>>
constexpr std::tuple<T, T, T> egcd(A a, B b) {
static_assert(std::is_integral<A>::value, "arguments to egcd are integers");
static_assert(std::is_integral<B>::value, "arguments to egcd are integers");
if (b == 0) {
return std::make_tuple(a, 1, 0);
} else {
auto triple = egcd(b, a%b);
return std::make_tuple(std::get<0>(triple), std::get<2>(triple), std::get<1>(triple) - (a/b) * std::get<2>(triple))
}
}
As you can see using <tuple>
makes the code very long and hard (compare with the Python version..) to read.
Any suggestions to make this code more readable?
std::array<T, N>
as an alternative. \$\endgroup\$