malachite_nz/integer/arithmetic/multi_crt.rs
1// Copyright © 2026 Mikhail Hogrefe
2//
3// Uses code adopted from the FLINT Library.
4//
5// Copyright © 2008, 2009 William Hart
6//
7// Copyright © 2010 Fredrik Johansson
8//
9// Copyright © 2021 Daniel Schultz
10//
11// This file is part of Malachite.
12//
13// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
14// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
15// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
16
17use crate::integer::Integer;
18use crate::natural::Natural;
19use crate::natural::arithmetic::multi_crt::MultiCrt;
20
21impl Integer {
22 /// Combines residues modulo pairwise-coprime moduli into the balanced representative: the
23 /// unique [`Integer`] $x$ with $-P/2 < x \leq P/2$, where $P$ is the moduli product, that is
24 /// congruent to each residue modulo the corresponding modulus. Returns `None` if the moduli are
25 /// unusable. The residues must be already reduced.
26 ///
27 /// The moduli are usable under the same conditions as for
28 /// [`Natural::multi_crt`](Natural::multi_crt), which produces the canonical representative
29 /// instead.
30 ///
31 /// $f((m_1, \ldots, m_k), (r_1, \ldots, r_k)) = \operatorname{Some}(x)$, where $-P/2 < x \leq
32 /// P/2$, $P = \prod_i m_i$, and $x \equiv r_i \mod m_i$ for all $i$, if the moduli are nonzero,
33 /// pairwise coprime, and, when there are at least two, none is 1.
34 ///
35 /// # Worst-case complexity
36 /// $T(n) = O(n (\log n)^3 \log\log n)$
37 ///
38 /// $M(n) = O(n \log n)$
39 ///
40 /// where $T$ is time, $M$ is additional memory, and $n$ is the number of significant bits of
41 /// the product of the moduli.
42 ///
43 /// # Panics
44 /// Panics if `moduli` is empty, if the number of values differs from the number of moduli, or
45 /// if any value is greater than or equal to its modulus.
46 ///
47 /// # Examples
48 /// ```
49 /// use malachite_base::num::basic::traits::{One, Two};
50 /// use malachite_nz::integer::Integer;
51 /// use malachite_nz::natural::Natural;
52 ///
53 /// // 8 is 2 mod 3 and 3 mod 5, and its balanced representative mod 15 is -7.
54 /// assert_eq!(
55 /// Integer::multi_balanced_crt(
56 /// &[Natural::from(3u32), Natural::from(5u32)],
57 /// &[Natural::TWO, Natural::from(3u32)],
58 /// ),
59 /// Some(Integer::from(-7))
60 /// );
61 /// assert_eq!(
62 /// Integer::multi_balanced_crt(
63 /// &[Natural::from(4u32), Natural::from(6u32)],
64 /// &[Natural::ONE, Natural::from(3u32)],
65 /// ),
66 /// None
67 /// );
68 /// ```
69 ///
70 /// This is fmpz_multi_CRT from fmpz/multi_CRT.c, FLINT 3.6.0, with sign = 1 and the residues
71 /// required to be reduced.
72 pub fn multi_balanced_crt(moduli: &[Natural], values: &[Natural]) -> Option<Self> {
73 Some(MultiCrt::new(moduli)?.apply_balanced(values))
74 }
75}