关于Exgcd
%%lkx
exgcd(扩展欧几里得)
可以用来判断并求解形如\(ax+by=c\)的方程,当且仅当\(gcd(a,b)|c\)时,存在整数解\(x,y\)
也就是说,\(exgcd\)可以用来求解方程\(ax+by=gcd(a,b)\),令\(a=b,b=a\%b\)则有方程\(b*x_1+(a\%b)*y_1=gcd(b,a\% b)\)
又因为\(gcd(a,b)=gcd(b,a\%b)\),且\(a\%b=a-b*\) \(\lfloor {a/b}\rfloor * y_1=gcd(a,b)\)
整理得:\(ay_1+b(x_1-\lfloor {a/b}\rfloor* y_1)=gcd(a,b)\)
所以原方程中: \(ay_1+ b(x_1-\lfloor {a/b}\rfloor *y_1)=gcd(a,b)\)
所以我们只需递归求\(x_1,y_1\),就能求出\(x,y\)
Code:
void exgcd(int a, int b, int &x, int &y) {
if(!b) {x = 1, y = 0;return;}
int d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
#include <cstdio>
#include <iostream>
using namespace std;
int a, b, x, y;
int read() {
int s = 0, w = 1;
char ch = getchar();
while(!isdigit(ch)) {if(ch == '-') w = -1; ch = getchar();}
while(isdigit(ch)) {s = s * 10 + ch - '0'; ch = getchar();}
return s * w;
}
void exgcd(int a, int b, int &x, int &y) {
if(!b) x = 1, y = 0;
else exgcd(b, a % b, y, x), y -= a / b * x;
}
int main() {
a = read(), b = read();
exgcd(a, b, x, y);
cout << (x + b) % b << endl;
return 0;
}
谢谢收看, 祝身体健康!