Skip to main content

malachite_base/num/arithmetic/
mod_div_list.rs

1// Copyright © 2026 Mikhail Hogrefe
2//
3// Uses code adopted from the FLINT Library.
4//
5//      Copyright © 2020 Daniel Schultz
6//
7// This file is part of Malachite.
8//
9// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
10// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
11// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
12
13use crate::num::arithmetic::mod_div::gcdinv;
14use crate::num::arithmetic::traits::ModDivList;
15use crate::num::basic::signeds::PrimitiveSigned;
16use crate::num::basic::unsigneds::PrimitiveUnsigned;
17use crate::num::conversion::traits::WrappingFrom;
18
19// Computes the solutions `q` of `qc ≡ b mod m` as `(start, stride, length)`: the solutions are
20// exactly `start + stride * i` for `0 <= i < length`, and `start` is the smallest. `b` and `c` must
21// be reduced mod `m`. Unlike a quotient from `mod_div`, the result is canonical: it does not depend
22// on the extended GCD's choice of cofactor.
23//
24// This is fmpz_divides_mod_list from fmpz/divides_mod_list.c, FLINT 3.6.0, where the inputs are
25// word-sized and reduced mod the modulus, and the solutions are returned as an Option.
26private_test_fn! {mod_div_list_unsigned<
27    U: WrappingFrom<S> + PrimitiveUnsigned,
28    S: PrimitiveSigned + WrappingFrom<U>,
29>(
30    b: U,
31    c: U,
32    m: U,
33) -> Option<(U, U, U)> {
34    assert!(b < m, "b must be reduced mod m, but {b} >= {m}");
35    assert!(c < m, "c must be reduced mod m, but {c} >= {m}");
36    // Solve d = cx + my, where d = gcd(c, m). (FLINT reduces the divisor mod m here; the
37    // precondition makes that a no-op.)
38    let (d, x) = gcdinv::<U, S>(c, m);
39    let (q, r) = b.div_rem(d);
40    if r != U::ZERO {
41        return None;
42    }
43    let stride = m / d;
44    let start = (x % stride).mod_mul(q % stride, stride);
45    Some((start, stride, d))
46}}
47
48macro_rules! impl_mod_div_list {
49    ($u:ident, $s:ident) => {
50        impl ModDivList<$u> for $u {
51            type Output = $u;
52
53            /// Finds all quotients of a number and another number modulo a third number $m$,
54            /// returning `None` if no quotient exists. The inputs must be already reduced modulo
55            /// $m$.
56            ///
57            /// A quotient exists if and only if $g = \gcd(y, m)$ divides $x$. In that case the
58            /// quotients are exactly the numbers $\text{start} + \text{stride} \cdot i$ for $0 \leq
59            /// i < \text{length}$, where $\text{start}$ is the smallest quotient, $\text{stride} =
60            /// m/g$, and $\text{length} = g$. Unlike the quotient returned by
61            /// [`ModDiv`](super::traits::ModDiv), the result is canonical.
62            ///
63            /// $f(x, y, m) = \operatorname{Some}((s, t, \ell))$, where $qy \equiv x \mod m$ if and
64            /// only if $q = s + ti$ for some $0 \leq i < \ell$, if such $q$ exist.
65            ///
66            /// # Worst-case complexity
67            /// $T(n) = O(n)$
68            ///
69            /// $M(n) = O(1)$
70            ///
71            /// where $T$ is time, $M$ is additional memory, and $n$ is `m.significant_bits()`: the
72            /// extended Euclidean algorithm on words performs $O(n)$ iterations of constant-cost
73            /// word operations, with no allocation.
74            ///
75            /// # Panics
76            /// Panics if `self` or `other` are greater than or equal to `m`.
77            ///
78            /// # Examples
79            /// See [here](super::mod_div_list#mod_div_list).
80            #[inline]
81            fn mod_div_list(self, other: $u, m: $u) -> Option<($u, $u, $u)> {
82                mod_div_list_unsigned::<$u, $s>(self, other, m)
83            }
84        }
85    };
86}
87apply_to_unsigned_signed_pairs!(impl_mod_div_list);