forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChinese_Remainder_Theorem.cpp
58 lines (45 loc) · 946 Bytes
/
Chinese_Remainder_Theorem.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
// A C++ program to demonstrate working of Chinese Remainder Theorem
// NAIVE IMPLEMENTATION
/*
s is size of num[] and rem[]. Returns the smallest
number a such that:
a % num[0] = rem[0],
a % num[1] = rem[1],
..................
a % num[s-1] = rem[s-1]
Assumption: Numbers in num[] are pairwise coprime
(gcd for every pair is 1)
*/
#include <iostream>
using namespace std;
int min(int num[], int rem[], int s)
{
int a = 1; // Initialize result
while(true)
{
int i;
for (i = 0; i < s; i++)
{
if(a%num[i] != rem[i])
break;
}
// If all remainders matched, we found a
if (i == s)
return a;
// Else try next number
a++;
}
return a;
}
// Driver function
int main()
{
int num[] = {3, 4, 5};
int rem[] = {2, 3, 1};
int s = sizeof(num) / sizeof(num[0]);
cout << "Number is " << min(num, rem, s);
return 0;
}
/* Output
Number is 11
*/