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

  1. Solve for recursively.

Lemma

  1. Applying the lemma yields that is a solution for .

This algorithm solves the problem in time and space.

std::pair<int, int> exgcd(int a, int b) {
	return [&](this 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);
}