Skip to main content

malachite_base/unsigned_polynomial/arithmetic/
mod_power_of_2.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::num::arithmetic::traits::{ModPowerOf2, ModPowerOf2Assign};
10use crate::num::basic::unsigneds::PrimitiveUnsigned;
11use crate::polynomial::Polynomial;
12use crate::unsigned_polynomial::UnsignedPolynomial;
13use alloc::vec::Vec;
14
15impl<T: PrimitiveUnsigned> ModPowerOf2 for UnsignedPolynomial<T> {
16    type Output = Self;
17
18    /// Divides every coefficient of a [`UnsignedPolynomial`] by $2^k$, keeping the remainders,
19    /// taking the polynomial by value.
20    ///
21    /// The result is reduced modulo $2^k$, which is to say that [`mod_power_of_2_is_reduced`](
22    /// crate::num::arithmetic::traits::ModPowerOf2IsReduced::mod_power_of_2_is_reduced) returns
23    /// `true` for it.
24    ///
25    /// Reducing can lower the degree, and can even give the zero polynomial: a leading coefficient
26    /// that is a multiple of $2^k$ becomes zero, and a polynomial does not hold trailing zero
27    /// coefficients. So $4x^2 + 3$ modulo $4$ is the constant $3$, not a quadratic with a zero
28    /// leading coefficient.
29    ///
30    /// $$
31    /// f(p, k) = q, \\quad \text{where} \\quad q_i = p_i - 2^k \left \lfloor \frac{p_i}{2^k}
32    /// \right \rfloor.
33    /// $$
34    ///
35    /// # Worst-case complexity
36    /// $T(n) = O(n)$
37    ///
38    /// $M(n) = O(1)$
39    ///
40    /// where $T$ is time, $M$ is additional memory, and $n$ is the number of coefficients.
41    ///
42    /// # Examples
43    /// ```
44    /// use core::str::FromStr;
45    /// use malachite_base::num::arithmetic::traits::ModPowerOf2;
46    /// use malachite_base::unsigned_polynomial::UnsignedPolynomial;
47    ///
48    /// // Every coefficient is taken modulo 2.
49    /// assert_eq!(
50    ///     UnsignedPolynomial::<u64>::from_str("x^2+3*x+2")
51    ///         .unwrap()
52    ///         .mod_power_of_2(1)
53    ///         .to_string(),
54    ///     "x^2+x"
55    /// );
56    ///
57    /// // Reducing the leading coefficient to zero lowers the degree.
58    /// assert_eq!(
59    ///     UnsignedPolynomial::<u64>::from_str("4*x^2+3")
60    ///         .unwrap()
61    ///         .mod_power_of_2(2)
62    ///         .to_string(),
63    ///     "3"
64    /// );
65    ///
66    /// // Modulo 2^0 every coefficient is zero, so the whole polynomial is.
67    /// assert_eq!(
68    ///     UnsignedPolynomial::<u64>::from_str("x^2+3*x+2")
69    ///         .unwrap()
70    ///         .mod_power_of_2(0)
71    ///         .to_string(),
72    ///     "0"
73    /// );
74    /// ```
75    #[inline]
76    fn mod_power_of_2(mut self, pow: u64) -> Self {
77        self.mod_power_of_2_assign(pow);
78        self
79    }
80}
81
82impl<T: PrimitiveUnsigned> ModPowerOf2 for &UnsignedPolynomial<T> {
83    type Output = UnsignedPolynomial<T>;
84
85    /// Divides every coefficient of a [`UnsignedPolynomial`] by $2^k$, keeping the remainders,
86    /// taking the polynomial by reference.
87    ///
88    /// See the documentation for the [`ModPowerOf2`] implementation on [`UnsignedPolynomial`] for
89    /// details, including how reducing can lower the degree.
90    ///
91    /// # Worst-case complexity
92    /// $T(n) = O(n)$
93    ///
94    /// $M(n) = O(n)$
95    ///
96    /// where $T$ is time, $M$ is additional memory, and $n$ is the number of coefficients.
97    ///
98    /// # Examples
99    /// ```
100    /// use core::str::FromStr;
101    /// use malachite_base::num::arithmetic::traits::ModPowerOf2;
102    /// use malachite_base::unsigned_polynomial::UnsignedPolynomial;
103    ///
104    /// let p = UnsignedPolynomial::<u64>::from_str("4*x^2+3").unwrap();
105    /// assert_eq!((&p).mod_power_of_2(2).to_string(), "3");
106    /// // The polynomial is left alone.
107    /// assert_eq!(p.to_string(), "4*x^2+3");
108    /// ```
109    #[inline]
110    fn mod_power_of_2(self, pow: u64) -> UnsignedPolynomial<T> {
111        // `from_coefficients_asc` trims, which is what makes the degree fall when the leading
112        // coefficient reduces to zero.
113        UnsignedPolynomial::from_coefficients_asc(
114            self.coefficients_asc()
115                .iter()
116                .map(|&c| c.mod_power_of_2(pow))
117                .collect::<Vec<_>>(),
118        )
119    }
120}
121
122impl<T: PrimitiveUnsigned> ModPowerOf2Assign for UnsignedPolynomial<T> {
123    /// Divides every coefficient of a [`UnsignedPolynomial`] by $2^k$, replacing the polynomial by
124    /// the one whose coefficients are the remainders.
125    ///
126    /// See the documentation for the [`ModPowerOf2`] implementation on [`UnsignedPolynomial`] for
127    /// details, including how reducing can lower the degree.
128    ///
129    /// # Worst-case complexity
130    /// $T(n) = O(n)$
131    ///
132    /// $M(n) = O(1)$
133    ///
134    /// where $T$ is time, $M$ is additional memory, and $n$ is the number of coefficients.
135    ///
136    /// # Examples
137    /// ```
138    /// use core::str::FromStr;
139    /// use malachite_base::num::arithmetic::traits::ModPowerOf2Assign;
140    /// use malachite_base::unsigned_polynomial::UnsignedPolynomial;
141    ///
142    /// let mut p = UnsignedPolynomial::<u64>::from_str("x^2+3*x+2").unwrap();
143    /// p.mod_power_of_2_assign(1);
144    /// assert_eq!(p.to_string(), "x^2+x");
145    ///
146    /// let mut p = UnsignedPolynomial::<u64>::from_str("4*x^2+3").unwrap();
147    /// p.mod_power_of_2_assign(2);
148    /// assert_eq!(p.to_string(), "3");
149    /// ```
150    fn mod_power_of_2_assign(&mut self, pow: u64) {
151        // A shortcut rather than a necessity: no `T` reaches its own width as a power, so wide is
152        // already the identity on every coefficient, and the loop below would do the same work to
153        // no effect.
154        if pow >= T::WIDTH {
155            return;
156        }
157        for c in &mut self.coefficients {
158            c.mod_power_of_2_assign(pow);
159        }
160        self.trim();
161    }
162}