#include<iostream>#include<algorithm>usingnamespace std;voidexgcd(int a,int b,int&x,int&y){if (!b){ x =1, y =0;return; }exgcd(b, a % b, y, x); y -= a / b * x;return;}intmain(){int n; cin >> n;while (n -- ){int a, b, x, y; cin >> a >> b;exgcd(a, b, x, y);printf("%d%d\n", x, y); }}
给定 n 组数据 ai,bi,mi,对于每组数求出一个 xi,使其满足 ai∗xi≡bi(modm),如果无解则输出 impossible。
由
ai∗xi≡bi(modm)
可得 ∃y∈Z
ax=my+b⇒ax+my′=b
由之前的贝祖等式可知,只要 gcd(a,m)∣b,我们就可以利用扩展欧几里得算法求解线性同余方程。
#include<iostream>#include<algorithm>usingnamespace std;voidexgcd(int a,int b,int&x,int&y){if (!b){ x =1, y =0;return; }exgcd(b, a % b, y, x); y -= a / b * x;}intmain(){int n; cin >> n;while (n -- ){int a, b, m; cin >> a >> b >> m;int x, y;exgcd(a, m, x, y);int gcd = a * x + m * y;if (b % gcd ==0) cout << (longlong)b / gcd * x % m << endl; else cout <<"impossible"<< endl; }}