中国剩余定理

模板代码:

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;
}
相关推荐
普通攻击往后拉6 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
@syh.7 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
可编程芯片开发7 小时前
基于零极点配置的PID控制系统simulink建模与仿真
算法
徐小夕8 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github
Hrain-AI8 小时前
2026 企业 AI 智能体平台横评:8 大主流平台 7 维度实测对比
人工智能·算法·机器学习
Angel Q.9 小时前
因子分析和生成模型有什么关系?从“幕后因素”到“生成数据”
算法
FBI HackerHarry浩10 小时前
AI大模型开发V2第四阶段线性回归
人工智能·算法·线性回归
Jerry11 小时前
LeetCode 108. 将有序数组转换为二叉搜索树
算法
蓝斯49712 小时前
Diff算法的简单介绍
算法