中国剩余定理

模板代码:

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;
}
相关推荐
不正经学生2 小时前
C语言预处理详解:编译器真正动手之前的那些事
c语言·开发语言·算法·面试·bug
毕竟是shy哥4 小时前
计算YOLO数据集中每个类的目标数
算法·yolo·机器学习
M78佐菲4 小时前
Linux学习笔记:TCP协议
linux·笔记·学习·tcp/ip·算法
晊晌_h6 小时前
嵌入式从0到精通——数据结构总结[特殊字符]
数据结构·算法·排序算法
我找到地球的支点啦6 小时前
Matlab系列(009) 一CRC循环冗余校验详解
开发语言·数据结构·算法·matlab·信息与通信
罗西的思考6 小时前
【OpenClaw具身硬件】ZeroClaw 源码阅读笔记(3)--- RAG
人工智能·算法·机器学习
浪里镖客7 小时前
位姿转换矩阵写法-个人习惯(计算机理解其实是相反的)
线性代数·算法·矩阵
小白羊丨10 小时前
如何诊断 Prompt 模板导致的效果下降?
人工智能·算法·prompt
OPEN-F11 小时前
C++11/14新特性精讲:移动语义与智能指针实战
开发语言·c++·算法
lisin-lee-cooper12 小时前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法