小时候最看不懂的一集
一、裴蜀定理
裴蜀定理:如果a与b均为整数,则有整数x和y使ax + by = gcd(a, b)
P4549 【模板】裴蜀定理 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
将处理为再接着一直处理
#include<bits/stdc++.h>
using namespace std;
const int N = 2e3 + 10;
int main() {
int n; cin >> n;
int ans = 0, res = 1;
for(int i = 1; i <= n; i++){
cin >> res;
if(res < 0) res = -res;
ans = __gcd(ans, res);
}
cout << ans << '\n';
}
二、线性丢番图方程
1.二元线性丢番图方程
定理:ax + by = c有解的充分必要条件是d = gcd(a, b)能整除c
2.扩展欧几里得算法
①判断方程ax + by = c是否有整数解,即d = gcd(a, b)能整除c
②用扩展欧几里得算法求ax + by = d的一个特解x0, y0
//返回d = gcd(a, b),并返回ax + by = d的特解x,y
ll extend_gcd(ll a, ll b, ll &x, ll &y){
if(b == 0){
x = 1;
y = 0;
return a;
}
ll d = extend_gcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
③在ax0 + by0 = d两边同时乘以c / d, 得ax0 c / d + by0 c / d = c
④对照ax + by = c,得特解(x0', y0') x0' = x0 c / d y0' = y0 c / d
⑤方程ax + by = c的通解为x = x0' + (b / d)n y = y0' + (a / d)n
例题P1516 青蛙的约会 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
extend_gcd()函数的参数需要是正数
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
//返回d = gcd(a, b),并返回ax + by = d的特解x,y
ll extend_gcd(ll a, ll b, ll &x, ll &y){
if(b == 0){
x = 1;
y = 0;
return a;
}
ll d = extend_gcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
int main(){
ll n, m, x, y, L; cin >> x >> y >> m >> n >> L;
ll a = n - m, c = x - y;
if(a < 0){
a = -a, c = -c;
}
ll d = extend_gcd(a, L, x, y);
if(c % d != 0) cout << "Impossible";
else cout << ((x * (c / d)) % (L / d) + (L / d)) % (L / d); //x的最小整数解
}
三、同余方程
求关于x的同余方程 ax ≡ 1 (mod b)的最小正整数解
P1082 [NOIP2012 提高组] 同余方程 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
//返回d = gcd(a, b),并返回ax + by = d的特解x,y
ll extend_gcd(ll a, ll b, ll &x, ll &y){
if(b == 0){
x = 1;
y = 0;
return a;
}
ll d = extend_gcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
//求逆
ll mod_inverse(ll a, ll m){
ll x, y;
extend_gcd(a, m, x, y);
//返回最小正整数
return (x % m + m) % m;
}
int main() {
ll a, m; cin >> a >> m;
cout << mod_inverse(a, m);
}