|
| 1 | +//this program is to implement Chinese Remainder Theorem |
| 2 | +public class ChineseRemainderTheorem |
| 3 | +{ |
| 4 | + |
| 5 | + //function to find the greatest common divisor (GCD) of two numbers using the Extended Euclidean Algorithm |
| 6 | + private static long gcd(long a, long b) |
| 7 | + { |
| 8 | + if(b == 0) |
| 9 | + return a; //base case: if b is 0, a is the GCD |
| 10 | + |
| 11 | + return gcd(b, a%b);//calling recursively |
| 12 | + } |
| 13 | + |
| 14 | + //function to find the modular inverse of 'a' under modulo 'm' using the Extended Euclidean Algorithm |
| 15 | + private static long extendedGCD(long a, long b) |
| 16 | + { |
| 17 | + long originalB = b; //keeping original 'b' for later use |
| 18 | + long x1 = 1, x2 = 0; //x1 and x2 are coefficients for 'a' |
| 19 | + long y1 = 0, y2 = 1; //y1 and y2 are coefficients for 'b' |
| 20 | + |
| 21 | + while(b != 0) |
| 22 | + { |
| 23 | + long q = a/b; //quotient |
| 24 | + long temp = b; //temporary variable to hold value of 'b' |
| 25 | + b = a % b; //remainder |
| 26 | + a = temp; //updating 'a' with previous value of 'b' |
| 27 | + |
| 28 | + //updating coefficients x1, x2, y1, y2 |
| 29 | + temp = x2; |
| 30 | + x2 = x1 - q*x2; //updating x2 with the quotient |
| 31 | + x1 = temp; |
| 32 | + |
| 33 | + temp = y2; |
| 34 | + y2 = y1 - q*y2; //updating y2 with the quotient |
| 35 | + y1 = temp; |
| 36 | + } |
| 37 | + //ensuring the result is positive |
| 38 | + return (x1 < 0)? (x1+originalB) : x1; |
| 39 | + } |
| 40 | + |
| 41 | + //function to implement the Chinese Remainder Theorem |
| 42 | + public static long chineseRemainder(int[] n, int[] a) |
| 43 | + { |
| 44 | + long N = 1; //variable to hold the product of all moduli |
| 45 | + for(int ni : n) |
| 46 | + N *= ni; //calculating the product of all moduli |
| 47 | + |
| 48 | + long result = 0; //variable to accumulate the final result |
| 49 | + for (int i = 0; i < n.length; i++) |
| 50 | + { |
| 51 | + long Ni = N/n[i]; //calculating Ni (the product of all moduli except n[i]) |
| 52 | + long mi = extendedGCD(Ni, n[i]); //finding the modular inverse of Ni modulo n[i] |
| 53 | + //updating the result |
| 54 | + result += a[i]*Ni*mi; |
| 55 | + } |
| 56 | + |
| 57 | + return result%N; //returning final answer |
| 58 | + } |
| 59 | + |
| 60 | + public static void main(String[] args) |
| 61 | + { |
| 62 | + //example test case |
| 63 | + int[] n = {3, 5, 7}; //moduli |
| 64 | + int[] a = {2, 3, 2}; //remainders |
| 65 | + |
| 66 | + //calculating the solution using the Chinese Remainder Theorem |
| 67 | + long solution = chineseRemainder(n, a); |
| 68 | + //output |
| 69 | + System.out.println("The solution is: " + solution); //expected output: 23 |
| 70 | + } |
| 71 | +} |
0 commit comments