-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChineseRemainderTheorem.cpp
51 lines (43 loc) · 938 Bytes
/
ChineseRemainderTheorem.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
#include <bits/stdc++.h>
using namespace std;
int calculateGCD(int a, int b, int *x, int *y){
if(b==0){
*x = 1;
*y = 0;
return a;
}
int tempX, tempY;
int gcd = calculateGCD(b, a%b, &tempX, &tempY);
*x = tempY;
*y = tempX - (a/b) * tempY;
return gcd;
}
int MMI(int a, int m) {
int x, y;
int gcd = calculateGCD(a, m, &x, &y);
if(gcd != 1) {
cout << "Not Possible" << endl;
return -1;
} else {
x = (x%m + m) % m;
return x;
}
}
int ChineseRemainder(int num[], int rem[]) {
int size = 3;
int product = 1;
for (int i = 0; i < size; i++)
product *= num[i];
int CR = 0;
for (int i = 0; i < size; i++)
CR += rem[i] * (product / num[i]) * MMI((product / num[i]), num[i]);
CR %= product;
return CR;
}
int main() {
int num[] = {3, 4, 5};
int rem[] = {2, 3, 1};
int chineseRemainder = ChineseRemainder(num, rem);
cout << chineseRemainder << endl;
return 0;
}