-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrt.cpp
More file actions
70 lines (55 loc) · 1.11 KB
/
Copy pathcrt.cpp
File metadata and controls
70 lines (55 loc) · 1.11 KB
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
#include <iostream>
#include <fstream>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <bitset>
#include <complex>
typedef long long ll;
typedef long double ld;
using namespace std;
// extended euclidean algorithm
// given a and b
// computes integers x and y such that
// a*x + b*y = g
// g = gcd(a,b);
void eed(ll a, ll b, ll *x, ll *y, ll *g){
if(a == 0){
*x = 0, *y = 1 , *g = b;
return;
}
ll x1,y1;
eed(b%a, a, &x1, &y1, g);
*x = y1 - (b/a)*x1;
*y = x1;
}
// finds the solution to the system
// x = a0 (mod n0)
// x = a1 (mod n1)
// ...
// x = a_{k-1} (mod n_{k-1})
// where ni and nj are coprime for i != j
// a and n are arrays of the same size, k is the length
ll crt(ll* a, ll* n, int k){
ll P = 1; // will hold prod of all n_i
for(int i=0; i<k; i++) P*=n[i];
ll x = 0;
for(int i=0; i<k; i++){
ll M, m, g, Ni = P/n[i];
eed(Ni , n[i], &M, &m, &g);
x += a[i] * M % P * Ni % P;
x %= P;
}
return x % P;
}
int main(){
ll a[3] = {2,3,2};
ll n[3] = {3,5,7};
ll x = crt(a, n, 3);
cout << x << endl;
return 0;
}