The Extended Euclidean Algorithm is an algorithm that finds a pair of integers and such that for non-negative integers and in time and space.
Algorithm
Lemma
-
Solve for recursively.
-
is a solution for .
Proof
Applying the lemma yields
Since
it follows that is a solution for .
This algorithm solves the problem in time and space.
std::pair<int, int> extended_euclidean(int a, int b) {
return y_combinator([&](auto &&self, int a, int b) -> std::pair<int, int> {
if (!b) {
return {1, 0};
}
auto [x, y] = self(b, a % b);
return {y, x - a / b * y};
})(a, b);
}Proof
If ,