-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChinese remainder.cpp
71 lines (44 loc) · 1.06 KB
/
Chinese remainder.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include<bits/stdc++.h>
using namespace std;
long long a[100], b[100], n;
long long modInverse(long long a, long long m)
{
long long m0 = m, t, q;
long long x0 = 0LL, x1 = 1LL;
if (m == 1) return 0;
while (a > 1)
{
q = a / m;
t = m;
m = a % m, a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
if (x1 < 0) x1 += m0;
return x1;
}
long long solve()
{
long long product = 1LL, res = 0, i;
for (i = 0; i<n; i++) product *= a[i];
for (i = 0; i<n; i++)
{
long long tmp = product / a[i];
// cout<<tmp<<" "<<a[i]<<" "<<modInverse(tmp, a[i])<<endl;
res += b[i] * modInverse(tmp, a[i]) * tmp;
}
return res % product;
}
int main()
{
int test, cs = 0;
scanf("%d", &test);
while(test--)
{
scanf("%lld", &n);
for(int i = 0; i<n; i++) scanf("%lld %lld", &a[i], &b[i]);
printf("Case %d: %lld\n", ++cs, solve());
}
return 0;
}