File tree Expand file tree Collapse file tree
src/main/java/com/williamfiset/algorithms/math Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11/**
2- * Solve a set of congruence equations using the Chinese Remainder Theorem.
2+ * Solve a set of congruence equations using the Chinese Remainder Theorem (CRT).
3+ *
4+ * Given a system of simultaneous congruences:
5+ *
6+ * x ≡ a_0 (mod m_0)
7+ * x ≡ a_1 (mod m_1)
8+ * ...
9+ * x ≡ a_{n-1} (mod m_{n-1})
10+ *
11+ * where all moduli m_i are pairwise coprime (gcd(m_i, m_j) = 1 for i ≠ j), the CRT guarantees a
12+ * unique solution x modulo M = m_0 * m_1 * ... * m_{n-1}.
13+ *
14+ * The solution is constructed as x = sum of a_i * M_i * y_i (mod M), where M_i = M / m_i and y_i
15+ * is the modular inverse of M_i modulo m_i (found via the extended Euclidean algorithm). Each term
16+ * contributes a_i for the i-th congruence and vanishes (mod m_j) for all j ≠ i, so the sum
17+ * satisfies every equation simultaneously.
18+ *
19+ * When moduli are not pairwise coprime, the system must first be reduced. Each modulus is split
20+ * into prime-power factors (e.g. 12 = 4 * 3), converting one equation into several with
21+ * prime-power moduli. Redundant equations are removed and conflicting ones detected. After
22+ * reduction, the moduli are pairwise coprime and the standard CRT applies.
23+ *
24+ * The eliminateCoefficient method handles equations of the form cx ≡ a (mod m) by dividing through
25+ * by gcd(c, m) — which is only possible when gcd(c, m) divides a — and then multiplying by the
26+ * modular inverse of the reduced coefficient.
327 *
428 * @author Micah Stairs
529 */
You can’t perform that action at this time.
0 commit comments