扩展欧几里德
文艺复兴
在\(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;
}