为什么会出现扩展欧几里得?
二元一次方程组求解
就是为了求 二元一次方程的整数解 ,
二元一次方程(ax + by = c)有解的充要条件就是 c 是 gcd(a, b) 的整数倍(称为 斐蜀定理)
然后我们就可以通过扩展欧几里得来求一个解,

然后我们终点的式子是可以确定的,x = 1 , y = 0, 然后再通过x, y 转移得到最初的x, y就得到了一组特解,x0, y0
通解为

裸题
//扩展欧几里得
#include<iostream>
#include<cstring>
#include<math.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
typedef long long ll;
ll ex_gcd(ll a, ll b, ll &x, ll &y){
if(!b){
x = 1;
y = 0;
return a;
}
ll d = ex_gcd(b, a%b, x, y);
ll t = x;
x = y;
y = t - (a/b) * y;
return d;
}
void solve(ll a, ll b, ll c){
ll x, y;
ll d = ex_gcd(a, b, x, y); // d是 a,b最大公约数
if( c % d ){ //无解情况
cout << "Impossible" << endl;
return ;
}
x = x * c / d; // 求一个解 因为你之前求的 gcd(a,b)的解,所以现在需要乘c。
ll t = b / d;
if(t < 0)
t = -t;
x = (x%t + t) % t;
cout << x << endl;
return ;
}
int main(){
int x, y, m, n, L;
while(cin >> x >> y >> m >> n >> L){
solve(m-n, L, y-x);
}
return 0;
}
求逆元
ll ex_gcd(ll a, ll b, ll &x, ll &y){
if(!b){
x = 1;
y = 0;
return a;
}
ll d = ex_gcd(b, a%b, x, y);
ll t = x;
x = y;
y = t - (a/b) * y;
return d;
}
ll inv(ll a, ll m){
ll x, y;
ll d = ex_gcd(a, m, x, y);
x = (x % m + m) % m;
return x;
}
求 |x|+|y| 的最小值
const ll INF = 0x3f3f3f3f;
ll ex_gcd(ll a, ll b, ll &x, ll &y){
if(!b){
x = 1;
y = 0;
return a;
}
ll d = ex_gcd(b, a%b, x, y);
ll t = x;
x = y;
y = t - (a/b) * y;
return d;
}
void solve(ll a, ll b, ll c){
bool flag = 0;
if(a < b){
int temp;
temp = a;
a = b;
b = temp;
flag = 1;
}
ll x, y;
ll x0, y0, min_x, min_y;
ll min;
ll d = ex_gcd(a, b, x0, y0);
if(c % d){
cout << " " << endl;
return ;
}
ll k = c/d;
x0 *= k;
y0 *= k;
ll xplus = b/d;
ll yplus = a/d;
int t= y0 / (a/d);//y=y0-a*t/d;t为此值时符合要求
min = INF;
for(int i = t-1; i <= t+1; i++){
x = fabs(x0 + xplus * i);
y = fabs(y0 - yplus * i);
if((x + y) < min){
min_x = x;
min_y = y;
min = x + y;
}
}
if(flag){
cout << min_y << " " << min_x << endl;
}else{
cout << min_x << " " << min_y << endl;
}
return ;
}
求 当x 最下 或者 y的最小整数解
ll ex_gcd(ll a, ll b, ll &x, ll &y){
if(!b){
x = 1;
y = 0;
return a;
}
ll d = ex_gcd(b, a%b, x, y);
ll t = x;
x = y;
y = t - (a/b) * y;
return d;
}
void solve(ll a, ll b, ll c){
bool flag = 0;
if(a < b){
int temp;
temp = a;
a = b;
b = temp;
flag = 1;
}
ll x, y;
ll x0, y0, min_x, min_y;
ll min;
ll d = ex_gcd(a, b, x0, y0);
if(c % d){
cout << " " << endl;
return ;
}
ll k = c/d;
x0 *= k;
y0 *= k;
ll xplus = b/d;
ll yplus = a/d;
if(xplus < 0) xplus = -xplus;
if(yplus < 0) yplus = -yplus;
//X = x + t * (b/gcd),Y = y - t * (a/gcd) , t为任意整数
//x = (x % xplus + xplus) % xplus;
//y = c - a * x; //x的最小正整数解
//y = (y % yplus + yplus) % yplus;
//x = c - b * y; //y的最小正整数解
return ;
}
本文详细介绍了扩展欧几里得算法的应用场景及其解决二元一次方程组的方法,包括求解整数解的过程、求逆元及特定条件下的最小值问题。

1万+

被折叠的 条评论
为什么被折叠?



