|
| 1 | +package remainder; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class ChineseRemainderTheorem { |
| 6 | + |
| 7 | + // Helper function to compute the greatest common divisor (GCD) |
| 8 | + public static int gcd(int a, int b) { |
| 9 | + if (b == 0) return a; |
| 10 | + return gcd(b, a % b); |
| 11 | + } |
| 12 | + |
| 13 | + // Helper function to compute the modular inverse of a modulo m |
| 14 | + // Uses the extended Euclidean algorithm |
| 15 | + public static int modInverse(int a, int m) { |
| 16 | + int m0 = m, t, q; |
| 17 | + int x0 = 0, x1 = 1; |
| 18 | + |
| 19 | + if (m == 1) return 0; |
| 20 | + |
| 21 | + while (a > 1) { |
| 22 | + // q is quotient |
| 23 | + q = a / m; |
| 24 | + t = m; |
| 25 | + |
| 26 | + // m is remainder now, process same as Euclid's algo |
| 27 | + m = a % m; |
| 28 | + a = t; |
| 29 | + t = x0; |
| 30 | + |
| 31 | + x0 = x1 - q * x0; |
| 32 | + x1 = t; |
| 33 | + } |
| 34 | + |
| 35 | + // Make x1 positive |
| 36 | + if (x1 < 0) x1 += m0; |
| 37 | + |
| 38 | + return x1; |
| 39 | + } |
| 40 | + |
| 41 | + // Function to find the smallest x that satisfies |
| 42 | + // the given system of congruences using the Chinese Remainder Theorem |
| 43 | + public static int findMinX(int[] num, int[] rem, int k) { |
| 44 | + // Compute product of all numbers |
| 45 | + int prod = 1; |
| 46 | + for (int i = 0; i < k; i++) prod *= num[i]; |
| 47 | + |
| 48 | + // Initialize result |
| 49 | + int result = 0; |
| 50 | + |
| 51 | + // Apply the formula: |
| 52 | + // result = (a1 * N1 * m1 + a2 * N2 * m2 + ... + ak * Nk * mk) % prod |
| 53 | + for (int i = 0; i < k; i++) { |
| 54 | + int pp = prod / num[i]; // Compute Ni = N / ni |
| 55 | + result += rem[i] * pp * modInverse(pp, num[i]); |
| 56 | + } |
| 57 | + |
| 58 | + return result % prod; |
| 59 | + } |
| 60 | + |
| 61 | + public static void main(String[] args) { |
| 62 | + // Example case |
| 63 | + int[] num = {3, 5, 7}; // Moduli |
| 64 | + int[] rem = {2, 3, 2}; // Remainders |
| 65 | + int k = num.length; |
| 66 | + |
| 67 | + // Calculate and print the result |
| 68 | + int result = findMinX(num, rem, k); |
| 69 | + System.out.println("The smallest x that satisfies the given system of congruences is: " + result); |
| 70 | + } |
| 71 | +} |
0 commit comments