Skip to main content

malachite_nz/integer_polynomial/conversion/
from_natural_polynomial.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_polynomial::IntegerPolynomial;
11use crate::natural_polynomial::NaturalPolynomial;
12use malachite_base::polynomial::Polynomial;
13
14impl From<NaturalPolynomial> for IntegerPolynomial {
15    /// Converts a [`NaturalPolynomial`] to an [`IntegerPolynomial`].
16    ///
17    /// Every polynomial with [`Natural`](crate::natural::Natural) coefficients is one with
18    /// [`Integer`] coefficients, so nothing is lost and nothing can fail. The coefficients are
19    /// converted one by one, and the leading one stays nonzero, so the degree is unchanged.
20    ///
21    /// $f(p) = p$, read on the left over $\N$ and on the right over $\Z$.
22    ///
23    /// # Worst-case complexity
24    /// $T(n) = O(n)$
25    ///
26    /// $M(n) = O(n)$
27    ///
28    /// where $T$ is time, $M$ is additional memory, and $n$ is the total number of bits of the
29    /// coefficients.
30    ///
31    /// # Examples
32    /// ```
33    /// use core::str::FromStr;
34    /// use malachite_nz::integer_polynomial::IntegerPolynomial;
35    /// use malachite_nz::natural_polynomial::NaturalPolynomial;
36    ///
37    /// let p = NaturalPolynomial::from_str("x^2+3*x+2").unwrap();
38    /// assert_eq!(IntegerPolynomial::from(p).to_string(), "x^2+3*x+2");
39    ///
40    /// assert_eq!(
41    ///     IntegerPolynomial::from(NaturalPolynomial::default()).to_string(),
42    ///     "0"
43    /// );
44    /// ```
45    #[inline]
46    fn from(p: NaturalPolynomial) -> Self {
47        // The coefficients keep their order and their nonzero leading one, so no trimming is
48        // needed; but going through the constructor costs one comparison and cannot be wrong.
49        Self::from_coefficients_asc(
50            p.into_coefficients_asc()
51                .into_iter()
52                .map(Integer::from)
53                .collect(),
54        )
55    }
56}