Skip to main content

lib_jsl_number_theory/
chinese_remainder_theorem.rs

1//! The Chinese remainder theorem.
2//!
3//! See the book entry [Divisibility and modular arithmetic](https://jwkunz.github.io/lib_jsl/book/number-theory/modular-arithmetic.html).
4
5use crate::greatest_common_divisor::extended_gcd;
6use lib_jsl_core::ErrorsJSL;
7
8/// Solves the simultaneous congruences `x ≡ r_i (mod m_i)` and returns `(x, M)` with
9/// `0 ≤ x < M`, where `M = lcm(m_i)`, so that the solution set is `x + kM`. The moduli need not
10/// be pairwise coprime (Garner-style pairwise merging with `gcd`); returns an error when the
11/// congruences are inconsistent or `M` overflows `i128`.
12pub fn chinese_remainder(residues: &[i128], moduli: &[i128]) -> Result<(i128, i128), ErrorsJSL> {
13    if residues.len() != moduli.len() {
14        return Err(ErrorsJSL::IncompatibleArraySizes((residues.len(), moduli.len())));
15    }
16    if moduli.iter().any(|&m| m <= 0) {
17        return Err(ErrorsJSL::InvalidInputRange("Moduli must be positive."));
18    }
19    let (mut x, mut m) = (0i128, 1i128);
20    // ANCHOR: crt_merge
21    for (&r, &mi) in residues.iter().zip(moduli) {
22        let r = r.rem_euclid(mi);
23        // Merge x (mod m) with r (mod mi): x + m t ≡ r (mod mi), i.e. m t ≡ r − x (mod mi).
24        let (g, p, _) = extended_gcd(m, mi);
25        let difference = r - x;
26        if difference % g != 0 {
27            return Err(ErrorsJSL::InvalidInputRange("The congruences are inconsistent."));
28        }
29        let step = mi / g;
30        // t = (difference / g) · p (mod mi / g), with p the inverse of m/g modulo mi/g.
31        let t = ((difference / g) % step * (p % step)).rem_euclid(step);
32        let lcm = m.checked_mul(step).ok_or(ErrorsJSL::InvalidInputRange("The combined modulus overflows."))?;
33        x = (x + m.checked_mul(t).ok_or(ErrorsJSL::InvalidInputRange("The combined modulus overflows."))?).rem_euclid(lcm);
34        m = lcm;
35    }
36    // ANCHOR_END: crt_merge
37    Ok((x, m))
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn solves_coprime_and_non_coprime_systems() {
46        // Sunzi's problem: x ≡ 2 (3), 3 (5), 2 (7) → 23 mod 105.
47        assert_eq!(chinese_remainder(&[2, 3, 2], &[3, 5, 7]).unwrap(), (23, 105));
48        // Non-coprime but consistent: x ≡ 3 (4), 5 (6) → 11 mod 12.
49        assert_eq!(chinese_remainder(&[3, 5], &[4, 6]).unwrap(), (11, 12));
50        // Negative residues are reduced first.
51        assert_eq!(chinese_remainder(&[-1, -1], &[5, 7]).unwrap(), (34, 35));
52        // Large moduli near 2⁶².
53        let (m1, m2) = (4_611_686_018_427_387_847i128, 4_611_686_018_427_387_817i128);
54        let (x, m) = chinese_remainder(&[123_456_789, 987_654_321], &[m1, m2]).unwrap();
55        assert_eq!((x % m1, x % m2, m), (123_456_789, 987_654_321, m1 * m2));
56        assert!(chinese_remainder(&[1, 2], &[4, 6]).is_err()); // inconsistent parity
57        assert!(chinese_remainder(&[1], &[0]).is_err() && chinese_remainder(&[1], &[2, 3]).is_err());
58        assert_eq!(chinese_remainder(&[], &[]).unwrap(), (0, 1));
59    }
60
61    #[test]
62    fn brute_force_agreement() {
63        for a in 0..8 {
64            for b in 0..12 {
65                let brute = (0..24).find(|x| x % 8 == a && x % 12 == b);
66                match chinese_remainder(&[a, b], &[8, 12]) {
67                    Ok((x, m)) => assert_eq!((Some(x), m), (brute, 24)),
68                    Err(_) => assert!(brute.is_none()),
69                }
70            }
71        }
72    }
73}