ztzAcWing 203. 同余方程(扩展欧几里得 dfs换系数) - AcWing
这篇题解讲的很详细
熟悉模板
#include <iostream>
using namespace std;
int exgcd(int a, int b, int &x, int &y) {
if (!b) {
x = 1, y = 0;
return a;
}
int d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
int main() {
int a, b, x, y;
cin >> a >> b;
exgcd(a, b, x, y);
cout << (x % b + b) % b << endl;
}
#include <iostream>
#include <cmath>
using namespace std;
typedef long long LL;
LL exgcd(LL a, LL b, LL &x, LL &y) {
if (!b) {
x = 1, y = 0;
return a;
}
LL d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
int main() {
LL a, b, m, n, L, x, y;
cin >> a >> b >> m >> n >> L;
int d = exgcd(m - n, L, x, y); //得到的最大公约数是d 但是不为b-a这个真正方程的解
if ((b - a) % d)
cout << "Impossible";
else {
x *= (b - a) / d; //要先乘上去才是这个方程的解
LL t = abs(L / d); //是y的系数L要/d
cout << (x % t + t ) % t;
}
}