扩展欧几里得

对于 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值