-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChineseRemainderTheorem.cpp
More file actions
85 lines (66 loc) · 1.87 KB
/
Copy pathChineseRemainderTheorem.cpp
File metadata and controls
85 lines (66 loc) · 1.87 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h>
#include <stdlib.h>
long long xgcd_left(long long a, long long b) {
long long q, r, xx, yy, sign, x[100], y[100];
// Initializes the coefficients
x[0] = 1; x[1] = 0;
y[0] = 0; y[1] = 1;
sign = 1;
// As long as b != 0 we replace a by b and b by a%b.
// We also update the coefficients x and y.
while (b != 0) {
r = a%b;
q = a/b;
a = b;
b = r;
xx = x[1];
yy = y[1];
x[1] = q*x[1] + x[0];
y[1] = q*y[1] + y[0];
x[0] = xx;
y[0] = yy;
sign = -sign;
}
// Final computation of the coefficients
x[0] = sign*x[0];
y[0] = -sign*y[0];
// Return gcd(a,b)
return x[0];
}
long long crtPrecomputation(long long moduli[], long long multiplier[], int number) {
int i;
long long modulus = 1;
long long m;
long long M;
long long inverse;
for(i = 0; i < number; i++) modulus *= moduli[i];
for(i = 0; i < number; i++) {
m = moduli[i];
M = modulus/m;
inverse = xgcd_left(M, m);
multiplier[i] = inverse * M % modulus;
}
return modulus;
}
long long crt(long long moduli[], long long x[], int number) {
long long multiplier[number];
long long result = 0;
long long modulus = crtPrecomputation(moduli, multiplier, number);
int i;
for(i = 0; i < number; i++)
result = (result + multiplier[i] * x[i]) % modulus;
return result > 0 ? result : result + modulus;
}
int main() {
long long x[100], moduli[100], X;
int i, number;
printf("Please enter the number of congruence:");
scanf("%d", &number);
for(i = 0; i < number; i++) {
printf("Please enter a%d and m%d (whitespaced two number):", i, i);
scanf("%lld %lld", &x[i], &moduli[i]);
}
X = crt(moduli, x, number);
printf("The X is %lld.\n", X);
return 0;
}