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

Given 2n integers a1, a2, ..., an and m1, m2, ..., mn, find a smallest non-negative integer x that satisfies ∀i∈ [1, n], x≡mi (mod ai).

Input format
Line 1 contains the integer n.

Line 2 ... n + 1: Each i + 1 line contains two integers ai and mi, separated by spaces.

Output format
Output the smallest non-negative integer x, if x does not exist, then output −1.
If x exists, the data guarantees that x must be in the range of 64-bit integers.

Data range
1≤ai≤231−1,
0≤mi <ai
1≤n≤25
Input sample:
2
8 7
11 9
Output sample:
31

Analysis of the template Chinese remaining definition
:

x mod a1 = m1
x mod a2 = m2
=>
x=k1a1+m1
x=k2a2+m2

所以:k1a1+k2*(-a2)=m2-m1
设d=gcd(a1,-a2),y=(m2-m1)/d;

使k1,k2扩大y倍
k1=k1+k*a2/d
k2=k2+k*a1/d

带回原式
(k1+k*a2/d)*a1+(k2+k*a1/d)*(-a2)=m2-m1
k1a1-k2a2=m2-m1 
所以成立
最小非负整数解
k1=k1%abs(a2/d)
k2=k2%abs(a1/d)
代入 x=k1a1+m1
x=(k1+k*a2/d)*a1+m1
x=k1a1+m1+k*lcm(a2,a1)
设 k1a1=mo, lcm(a2,a1)=a0
所以 x=k*a0+m0;

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a1,m1,a2,m2;
int n;
ll 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;
}
int main()
{
	cin>>n;
	cin>>a1>>m1;
	for(int i=1;i<=n-1;i++)
	{
		cin>>a2>>m2;
		ll k1,k2;
		ll d=exgcd(a1,-a2,k1,k2);
		if((m2-m1)%d)
		{
			cout<<-1<<endl;
			break;
		}
		ll mod=abs(a2/d);
		k1=(k1*(m2-m1)/d%mod+mod)%mod;
		m1=k1*a1+m1;
		a1=abs(a1/d*a2);
	}
	cout<<m1<<endl;
 } 

Published 572 original articles · praised 14 · 10,000+ views

Guess you like

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