扩展欧几里德

文艺复兴

\(a\)\(b\)互质(即\(\gcd(a,b) = 1\))的情况下

\(ax \equiv 1 \pmod b\)

\(x\)

\(\because ax \equiv 1 \pmod b\)

\(\therefore ax - b(-y) = 1\)

\(\therefore ax + by = 1\)

\(\because \gcd(a,b) = 1\)

\(\therefore ax + by = \gcd(a, b)\)

\(\because \gcd(a, b) = \gcd(b, a \% b)\)

\[\begin{aligned} \therefore ax + by &= bx + (a \% b) y \\ &= bx + (a - \lfloor \dfrac a b \rfloor \times b) y \\ &= bx + ay - \lfloor \dfrac a b \rfloor by \\ &= ay + b(x - \lfloor \dfrac a b \rfloor y) \end{aligned} \]

\(\therefore x_1=y_2, y_1=x_2-\lfloor\dfrac{a}{b}\rfloor y_2\)

void exgcd(int a, int b, int &x, int &y) {
	if (!b) return x = 1, y = 0, void();
	exgcd(b, a % b, x, y);
	int t = x;
	x = y;
	y = t - a / b * y;
}
posted @ 2020-07-19 10:24  YouXam  阅读(222)  评论(3编辑  收藏  举报