扩展中国剩余定理
P4777 【模板】扩展中国剩余定理(EXCRT)
1 #include <cstdio>
2 #include <cstdlib>
3 #include <cmath>
4 #include <cstring>
5 #include <algorithm>
6 using namespace std;
7 #define ll long long
8 //#define int128 __int128
9
10 //typedef ll type;
11 typedef __int128 type;
12
13 ll c,x,y,_a2,_b2;
14 type a1,b1,a2,b2,a3;
15
16 void gcd(type a,type b)
17 {
18 if (b==0)
19 {
20 if ((b2-b1)%a!=0)
21 {
22 printf("-1\n");
23 exit(0);
24 }
25 c=a;
26 x=(b2-b1)/a;
27 y=0;
28 }
29 else
30 {
31 gcd(b,a%b);
32 type z;
33 z=x;
34 x=y;
35 y=z-a/b*y;
36 }
37 }
38
39 int main()
40 {
41 int n,i;
42 a1=1,b1=0;
43 scanf("%d",&n);
44 for (i=1;i<=n;i++)
45 {
46 scanf("%lld%lld",&_a2,&_b2); ///read __int128 can't use cin
47 a2=_a2,b2=_b2;
48 if (a2>a1)
49 swap(a1,a2),swap(b1,b2);
50 gcd(a1,a2);
51
52 a3=a1/c*a2;
53 b1=((a1*x+b1)%a3+a3)%a3;
54 a1=a3;
55 }
56 printf("%lld",(ll)b1);
57 return 0;
58 }