对于 ax + by = gcd(a,b) --> gcd(b,a%b) (由欧几里得算法知道)
即ax + by = bx + (a-a/b * b)y -> x = y, y = x - a/b *y 。可以用gcd计算,回溯的时候套用这个公式即可。
代码:
int exgcd(int a,int b,int &x,int &y){
if(b == 0){
x = 1,y = 0;
return a;
}
int d = exgcd(b,a%b,x,y);
int z = x; x = y; y = z - a/b*y;
return d;
}
同余方程:
题目可以化简为 ax + by = 1 求出最小正整数 x
代码:
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define int long long
#define sc scanf
#define pf printf
using namespace std;
typedef pair<int,int> pii;
typedef long long ll;
typedef unsigned long long LL;
const int INF = 0x3f3f3f3f;
const double eps = 1e-4;
const int mod = 1e9+9;
const int N = 200010;
int x,y;
int exgcd(int a,int b,int &x,int &y){
if(b == 0){
x = 1,y = 0;
return a;
}
int d = exgcd(b,a%b,x,y);
int z = x; x = y; y = z - a/b*y;
return d;
}
signed main(){
// IOS;
#ifdef ddgo
freopen("C:/Users/asus/Desktop/ddgoin.txt","r",stdin);
#endif
int a,b; cin>>a>>b;
exgcd(a,b,x,y);
cout<<(x%b+b)%b<<endl;//先把负数模到b能把它加到整数的范围内
return 0;
}