Expanding Chinese Remainder Theorem (EXCRT) -------------------------------------- Number Theory (Template)

Insert picture description here
Insert picture description here
Analysis: The
inference process uses int128
Insert picture description here
because multiplication will burst long long

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef __int128 uint128;
const int N=1e5+10000;
ll M[N],C[N],x,y;
int n;
ll gcd(ll a,ll b)
{
	return b ? gcd(b,a%b) : a;
}
uint128 exgcd(ll a,ll b,ll &x,ll &y)
{
	if(!b)
	{
		x=1;y=0;
		return a;
	 } 
	 ll d=exgcd(b,a%b,x,y);
	 ll tmp=x;
	 x=y;
	 y=tmp-a/b*y;
	 return d;
} 
uint128 inv(ll a,ll b)
{
	ll r=exgcd(a,b,x,y);
	while(x<0) x+=b;
	return x;
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%lld %lld",&M[i],&C[i]);
	}
	for(int i=2;i<=n;i++)
	{
		ll M1=M[i-1],M2=M[i],C1=C[i-1],C2=C[i] ;
		ll t=gcd(M1,M2);
		if((C2-C1)%t!=0)
		{
			break;
		}
		M[i]=M2/t*M1;
		C[i]=((C2-C1)/t*inv(M1/t,M2/t))%(M2/t)*M1+C1;
		C[i]=(C[i]%M[i]+M[i])%M[i];
	}
	cout<<C[n]<<endl;
} 
Published 572 original articles · praised 14 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/105373668