Skip to main content

malachite_nz/integer_polynomial/arithmetic/
is_unit.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_polynomial::IntegerPolynomial;
10use malachite_base::num::arithmetic::traits::IsUnit;
11
12impl IsUnit for IntegerPolynomial {
13    /// Determines whether an [`IntegerPolynomial`] is a unit: whether it is the constant polynomial
14    /// 1 or $-1$, the only polynomials with integer coefficients that have a multiplicative
15    /// inverse.
16    ///
17    /// # Worst-case complexity
18    /// Constant time and additional memory.
19    ///
20    /// # Examples
21    /// ```
22    /// use core::str::FromStr;
23    /// use malachite_base::num::arithmetic::traits::IsUnit;
24    /// use malachite_base::num::basic::traits::Zero;
25    /// use malachite_base::polynomial::Polynomial;
26    /// use malachite_nz::integer_polynomial::IntegerPolynomial;
27    ///
28    /// assert_eq!(IntegerPolynomial::one().is_unit(), true);
29    /// assert_eq!(IntegerPolynomial::negative_one().is_unit(), true);
30    /// assert_eq!(IntegerPolynomial::ZERO.is_unit(), false);
31    /// assert_eq!(IntegerPolynomial::two().is_unit(), false);
32    /// assert_eq!(IntegerPolynomial::x().is_unit(), false);
33    /// assert_eq!(
34    ///     IntegerPolynomial::from_str("-x-1").unwrap().is_unit(),
35    ///     false
36    /// );
37    /// ```
38    fn is_unit(&self) -> bool {
39        match self.coefficients.as_slice() {
40            [c] => c.is_unit(),
41            _ => false,
42        }
43    }
44}