1. 程式人生 > >【模板】中國剩餘定理CRT

【模板】中國剩餘定理CRT

解析:

聯賽結束後統一更模板題題解。

程式碼:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define re register
#define gc getchar
#define pc putchar
#define cs const

inline int getint(){
	re int num;
	re char c;
	while(!isdigit(c=gc()));num=c^48;
	while(isdigit(c=gc()))num=(num<<1)+(num<<
3)+(c^48); return num; } inline ll quickpow(ll a,ll b,ll mod){ ll ans=1; for(;b;b>>=1,a=a*a%mod)if(b&1)ans=ans*a%mod; return ans; } inline ll inv(ll a,ll m){ return quickpow(a,m-2,m); } cs int N=11; ll mod[N],remain[N]; int n; ll m=1; inline int CRT(){ for(int re i=1;i<=n;++i)
m*=mod[i]; ll ans=0; for(int re i=1;i<=n;++i){ ans=(ans+(m/mod[i])*inv(m/mod[i],mod[i])%m*remain[i]%m)%m; } return ans; } signed main(){ n=getint(); for(int re i=1;i<=n;++i){ mod[i]=getint(); remain[i]=getint(); } cout<<CRT(); return 0; }