Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

CRT模板

用于求解线性同余方程组。

查看代码
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
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
const int N = 10;
int n;
LL res, mul = 1, A[N], B[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, y, x);
y -= a / b * x;
return d;
}
LL inv (LL a, LL b)
{
LL x, y;
exgcd(a, b, x, y);
return (x % b + b) % b;
}
int main ()
{

cin >> n;
for (int i = 0; i < n; i++)
{
cin >> A[i] >> B[i];
mul *= A[i];
}
for (int i = 0; i < n; i++)
res = (res + B[i] * (mul / A[i]) % mul * inv(mul / A[i], A[i]) % mul) % mul;
cout << res;
return 0;
}