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

  1. Solve for recursively.

  2. 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);
}