中国剩余定理

模板代码:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define fi first
#define se second
const ll mod=998244353;
const int N=2e5+10;
#define int ll


int n,m[300],r[300];
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,y,x);
	y-=a/b*x;
	return d;
}
ll crt(ll m[],ll r[]){
	ll M=1,ans=0;
	for(int i=1;i<=n;i++) M*=m[i];
	for(int i=1;i<=n;i++){
		ll c=M/m[i],x,y;
		exgcd(c,m[i],x,y);
		ans=(ans+r[i]*c*x%M)%M;
	}
	return (ans%M+M)%M;
}
void solve(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>m[i]>>r[i];
	}
	cout<<crt(m,r);
}

signed main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    int t=1;
    //cin>>t;
	while (t--){
		solve();
	}
	return 0;
}
相关推荐
洛水水17 小时前
【力扣100题】63.最小覆盖子串
算法·leetcode
AllData公司负责人17 小时前
亲测丝滑,体验跃迁|AllData通过集成开源项目RustFS,多模态数据存储新范式
java·大数据·数据库·算法·数据分析·rustfs
磊 子17 小时前
AVL树的讲解
数据结构·算法
Trouvaille ~17 小时前
【Redis篇】Hash 哈希:字段级操作与对象存储的最佳实践
数据库·redis·后端·算法·缓存·哈希算法·键值对
悠仁さん17 小时前
数据结构 树 二叉树 堆 (链式二叉树模拟实现篇)
数据结构·算法
z2005093018 小时前
今日算法(带回文问题的回溯)
算法·leetcode·回溯
洛水水18 小时前
【力扣100题】55.编辑距离
算法·leetcode·动态规划
洛水水18 小时前
【力扣100题】62.滑动窗口最大值
数据结构·算法·leetcode
IronMurphy18 小时前
算法五十一 64. 最小路径和
算法
醒醒该学习了!18 小时前
Prompt提示词——带有深度思考模型的提示方法(理论篇)
人工智能·算法·prompt