exgcd板子

#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = a; i <= b; ++i)
#define per(i, a, b) for(int i = a; i >= b; --i)
#define I inline
#define int long long
I int mul(int a, int b, int mod){
	if(b < 0) b = -b, a = -a;
	int res(0);
	while(b){
		if(b & 1) res = (res + a) % mod;
		b >>= 1;
		a = (a + a) % mod;
	}
	return res;
}
int n;
int exgcd(int a, int b, int &x, int &y){
	if(!b){ x = 1, y = 0; return a; }
	int gcd = exgcd(b, a % b, y, x);
	y -= a / b * x;
	return gcd;
}
signed main(){
	int a, b;
	cin >> n;
	int k1, k2, lcm(0), x, gcd;
	while(n--){
		cin >> a >> b;
		if(!lcm){
			lcm = a;
			x = b;
		}else{
			gcd = exgcd(lcm, a, k1, k2);
			int L = lcm;
			lcm = lcm / gcd * a;
			k1 = mul(k1, (b - x) / gcd, lcm);
			x = (x + mul(k1, L, lcm)) % lcm;
		}
	}
	if(x < 0) x += lcm;
	cout << x << endl;
	return 0;
}
posted @ 2022-02-12 15:21  __int256  阅读(41)  评论(0编辑  收藏  举报