1 基础知识
数学定理:对于任意正整数a和b,一定存在非零整数x和y,使得xa+yb=gcd(a,b)。
扩展欧几里得算法的关键步骤:
- 如果b为0,那么可取x = 1, y = 0。
- 否则,exgcd(b, a % b),它对应的结果为y和x,即yb + x (a % b) = gcd(b, a % b)。考虑到
a
%
b
=
a
−
⌊
a
b
⌋
⋅
b
a\%b=a-\lfloor \frac{a}{b} \rfloor \cdot b
a%b=a−⌊ba⌋⋅b,故,
y b + x ⋅ ( a % b ) = y b + x ⋅ ( a − ⌊ a b ⌋ ⋅ b ) = x a + ( y − ⌊ a b ⌋ ⋅ x ) ] ⋅ b yb + x \cdot (a \% b) = yb + x \cdot (a - \lfloor \frac{a}{b} \rfloor \cdot b ) =xa+(y-\lfloor \frac{a}{b} \rfloor \cdot x)]\cdot b yb+x⋅(a%b)=yb+x⋅(a−⌊ba⌋⋅b)=xa+(y−⌊ba⌋⋅x)]⋅b - 故得出递推公式,exgcd(a, b, x, y) ← exgcd(b, a % b, y, x)
x = x x = x x=x
y = y − a / b ⋅ x y = y - a / b \cdot x y=y−a/b⋅x
依据上述关键步骤,可以写出如下代码,
int exgcd(int a, int b, int &x, int &y) {
if (b == 0) {
x = 1;
y = 0;
return a;
} else {
int res = exgcd(b, a % b, y, x);
y -= a / b * x;
return res;
}
}
2 模板
// 求x, y,使得ax + by = gcd(a, b)
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;
}
3 工程化
题目1:求一组满足要求的x和y。
#include <iostream>
using namespace std;
int n;
int exgcd(int a, int b, int& x, int& y) {
if (b == 0) {
x = 1;
y = 0;
return a;
} else {
int res = exgcd(b, a % b, y, x);
y -= a / b * x;
return res;
}
}
int main() {
cin >> n;
while (n--) {
int a, b;
cin >> a >> b;
int x, y;
exgcd(a,b,x,y);
cout << x << " " << y << endl;
}
return 0;
}
题目2:求解线性同余方程。
#include <iostream>
using namespace std;
int n;
int exgcd(int a, int b, int &x, int &y) {
if (b == 0) {
x = 1;
y = 0;
return a;
} else {
int res = exgcd(b, a % b, y, x);
y -= a / b * x;
return res;
}
}
int main() {
cin >> n;
while (n--) {
int a, b, m;
cin >> a >> b >> m;
int x, y;
int d = exgcd(a, m, x, y);
if (b % d != 0) puts("impossible");
else {
int res = (long long)x * b / d % m;
cout << res << endl;
}
}
return 0;
}