Chinese Remainder Theorem
Write a C/C++ program to solve given simultaneous pairs of Linear Congruence Equations using the Chinese remainder theorem.
The Chinese remainder theorem is a theorem that gives a unique solution to simultaneous linear congruences with coprime moduli. In its basic form, the Chinese remainder theorem will determine a number p that, when divided by some given divisors, leaves given remainders.
Related Post:
For example,
Input:
x=2(mod 3)
x=3(mod 5)
x=2(mod 7)
Output: x = 233
The solution of the given equations is x=23(mod 105)
When we divide 233 by 105, we get the remainder of 23.
Input:
x=4(mod 10)
x=6(mod 13)
x=4(mod 7)
x=2(mod 11)
Output: x = 81204
The solution of the given equations is x=1124(mod 10010)
When we divide 81204 by 10010, we get the remainder of 1124
Input:
x=3(mod 7)
x=3(mod 10)
x=0(mod 12)
Output: The given equations has no solutions.
Implementation:
|
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 86 87 88 89 90 91 92 93 94 |
#include <stdio.h> #include <stdlib.h> // recursively calculate the GCD of two numbers int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } // function to determine whether a solution is possible int check(int b[], int n) { for (int x = 0; x < n; x++) { for (int y = x + 1; y < n; y++) { if (gcd(b[x], b[y]) != 1) { return 1; } } } return 0; } // Chinese Remainder Theorem int evaluate(int a[], int b[], int n) { int Minv[n]; int q, r, r1, r2, t, t1, t2; int total = 1; for (int k = 0; k < n; k++) { total *= b[k]; } for (int k = 0; k < n; k++) { r1 = b[k]; r2 = total / b[k]; t1 = 0; t2 = 1; while (r2 > 0) { q = r1 / r2; r = r1 - q * r2; r1 = r2; r2 = r; t = t1 - q * t2; t1 = t2; t2 = t; } if (r1 == 1) { Minv[k] = t1; } if (Minv[k] < 0) { Minv[k] = Minv[k] + b[k]; } } int x = 0; for (int k = 0; k < n; k++) { x += (a[k] * total * Minv[k]) / b[k]; } return x; } // main function int main() { int n = 4; // number of equations int a[n], b[n]; for (int i = 0; i < n; i++) { fscanf(stdin, "x=%d(mod %d)\n", &a[i], &b[i]); } if (!check(b, n)) { fprintf(stdout, "x = %d\n", evaluate(a, b, n)); } else { fprintf(stdout, "The given equations has no solutions.\n"); } return 0; } |
Input:
x=4(mod 10)
x=6(mod 13)
x=4(mod 7)
x=2(mod 11)
Output:
x = 81204
That’s all about the Chinese Remainder Theorem.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)