# 数学训练—-数论-寒假安排

Description
One day I was shopping in the supermarket. There was a cashier counting coins seriously when a little kid running and singing “门前大桥下游过一群鸭，快来快来 数一数，二四六七八”. And then the cashier put the counted coins back morosely and count again…
Hello Kiki is such a lovely girl that she loves doing counting in a different way. For example, when she is counting X coins, she count them N times. Each time she divide the coins into several same sized groups and write down the group size Mi and the number of the remaining coins Ai on her note.
One day Kiki’s father found her note and he wanted to know how much coins Kiki was counting.
Input
The first line is T indicating the number of test cases.
Each case contains N on the first line, Mi(1 <= i <= N) on the second line, and corresponding Ai(1 <= i <= N) on the third line.
All numbers in the input and output are integers.
1 <= T <= 100, 1 <= N <= 6, 1 <= Mi <= 50, 0 <= Ai < Mi
Output
For each case output the least positive integer X which Kiki was counting in the sample output format. If there is no solution then output -1.

Sample Input
2 2 14 57 5 56 5 19 54 40 24 80 11 2 36 20 76
Sample Output
Case 1: 341 Case 2: 5996

#include <iostream>
#include <stdio.h>
using namespace std;
long long ExGcd(long long a,long long b,long long &x,long long &y)
{
if(b==0)
{
x=1;y=0;
return a;
}
long long r=ExGcd(b,a%b,x,y);
long long t=x;
x=y;
y=t-a/b*y;
return r;
}
long long gcd(long long a,long long b)
{
return b==0?a:gcd(b,a%b);
}

long long CRT(long long r[],long long a[],int n)
{
long long rr=r;
long long aa=a;
for(int i=1;i<n;i++)
{
long long x,y;
long long C=r[i]-rr;
long long d=ExGcd(aa,a[i],x,y);
if((C%d)!=0) return -1;
long long Mod=a[i]/d;
x=((x*(C/d)%Mod)+Mod)%Mod;
rr=rr+aa*x;
aa=aa*a[i]/d;
}
if(rr==0)
{
rr=1;
for(int i=0;i<n;i++)
rr=rr*a[i]/gcd(rr,a[i]);
}
return rr;
}

int main()
{
int t,n;
cin>>t;
long long r,a;
for(int k=1;k<=t;k++)
{
cin>>n;
for(int i=0;i<n;i++)
scanf("%lld",&a[i]);
for(int i=0;i<n;i++)
scanf("%lld",&r[i]);
cout<<"Case "<<k<<": "<<CRT(r,a,n)<<endl;
}
return 0;
}

0