The Extended Euclidean Algorithm is an algorithm that finds a pair of integers and such that for integers and in time and space.

Algorithm

Lemma

Let and be integers such that

then applying the lemma yields

Since

it follows that if , .

This algorithm solves the problem in time and space.

int x = 1, y = 0;
y_combinator([&](auto &&self, int a, int b) -> void {
	if (!b) {
		return;
	}
 
	self(b, a % b);
	x = std::exchange(y, x - a / b * y);
})(a, b);
 
return {x, y};