malachite_nz/integer_vector/arithmetic/multi_crt.rs
1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::integer::Integer;
10use crate::integer_vector::IntegerVector;
11use crate::natural_vector::arithmetic::multi_crt::{
12 ElementCombiner, map_columns, multi_crt_combiner,
13};
14use crate::platform::Limb;
15use malachite_base::unsigned_vector::UnsignedVector;
16
17impl IntegerVector {
18 /// Combines vectors of residues modulo pairwise-coprime word-sized moduli into the vector whose
19 /// every element is the representative of smallest absolute value that is congruent to each of
20 /// its residues, returning `None` if the moduli are unusable.
21 ///
22 /// `residues[j]` holds the residues of every element modulo `moduli[j]`, so element $i$ of the
23 /// result is the combination of `residues[0][i]`, `residues[1][i]`, and so on, as
24 /// [`Integer::multi_balanced_crt`] would compute it. Each element $x$ of the result satisfies
25 /// $-M/2 < x \leq M/2$, where $M$ is the product of the moduli, so a tie at $M/2$ is positive.
26 /// The work that depends only on the moduli is done once, not once per element. The residues
27 /// must be already reduced, and the moduli are unusable under the conditions of
28 /// [`Integer::multi_balanced_crt`]: with one modulus, if it is 0; with more, if any is 0 or 1
29 /// or two are not coprime.
30 ///
31 /// For the representatives in $[0, M)$ instead, use
32 /// [`NaturalVector::multi_crt`](crate::natural_vector::NaturalVector::multi_crt).
33 ///
34 /// # Worst-case complexity
35 /// $T(n, d) = O(n (\log n)^3 \log\log n + dn (\log n)^2 \log\log n)$
36 ///
37 /// $M(n, d) = O(n \log n + dn)$
38 ///
39 /// where $T$ is time, $M$ is additional memory, $n$ is the number of significant bits of the
40 /// product of the moduli, and $d$ is the dimension of the residue vectors.
41 ///
42 /// # Panics
43 /// Panics if `moduli` is empty, if the number of residue vectors differs from the number of
44 /// moduli, if the residue vectors do not all have the same dimension, or if, when the moduli
45 /// are usable, any residue is greater than or equal to its modulus.
46 ///
47 /// # Examples
48 /// ```
49 /// use core::str::FromStr;
50 /// use malachite_base::unsigned_vector::UnsignedVector;
51 /// use malachite_nz::integer_vector::IntegerVector;
52 ///
53 /// // 23 is 2 mod 3, 3 mod 5, and 2 mod 7; 6 is 0, 1, and 6; and -5 is 1, 0, and 2.
54 /// let residues = [
55 /// UnsignedVector::from_str("(2, 0, 1)").unwrap(),
56 /// UnsignedVector::from_str("(3, 1, 0)").unwrap(),
57 /// UnsignedVector::from_str("(2, 6, 2)").unwrap(),
58 /// ];
59 /// assert_eq!(
60 /// IntegerVector::multi_balanced_crt(&[3, 5, 7], &residues)
61 /// .unwrap()
62 /// .to_string(),
63 /// "(23, 6, -5)"
64 /// );
65 ///
66 /// // 4 and 6 are not coprime.
67 /// assert!(IntegerVector::multi_balanced_crt(&[4, 6], &residues[..2]).is_none());
68 /// ```
69 ///
70 /// This is equivalent to `_fmpz_vec_multi_CRT_ui` from `fmpz_vec/multi_CRT_ui.c`, FLINT 3.6.0,
71 /// with sign = 1 and the residues required to be reduced.
72 pub fn multi_balanced_crt(moduli: &[Limb], residues: &[UnsignedVector<Limb>]) -> Option<Self> {
73 Some(Self {
74 elements: match multi_crt_combiner(moduli, residues)? {
75 // A residue above half the modulus is closer to zero once the modulus is
76 // subtracted; at exactly half, it stays positive.
77 ElementCombiner::Single(m) => residues[0]
78 .elements
79 .iter()
80 .map(|&r| {
81 if r > m >> 1 {
82 -Integer::from(m - r)
83 } else {
84 Integer::from(r)
85 }
86 })
87 .collect(),
88 ElementCombiner::Comb(comb) => {
89 map_columns(residues, |rs| comb.combine_balanced(rs))
90 }
91 },
92 })
93 }
94}