Skip to main content

malachite_nz/gaussian_integer/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::gaussian_integer::GaussianInteger;
10use malachite_base::num::arithmetic::traits::IsUnit;
11
12impl IsUnit for GaussianInteger {
13    /// Determines whether a [`GaussianInteger`] is a unit: one of $1$, $-1$, $i$, and $-i$, the
14    /// four elements of $\mathbb{Z}\[i\]$ with a multiplicative inverse in $\mathbb{Z}\[i\]$.
15    ///
16    /// # Worst-case complexity
17    /// Constant time and additional memory.
18    ///
19    /// # Examples
20    /// ```
21    /// use malachite_base::num::arithmetic::traits::IsUnit;
22    /// use malachite_base::num::basic::traits::{I, NegativeI, NegativeOne, One, Two, Zero};
23    /// use malachite_nz::gaussian_integer::GaussianInteger;
24    /// use std::str::FromStr;
25    ///
26    /// assert_eq!(GaussianInteger::ONE.is_unit(), true);
27    /// assert_eq!(GaussianInteger::NEGATIVE_ONE.is_unit(), true);
28    /// assert_eq!(GaussianInteger::I.is_unit(), true);
29    /// assert_eq!(GaussianInteger::NEGATIVE_I.is_unit(), true);
30    /// assert_eq!(GaussianInteger::ZERO.is_unit(), false);
31    /// assert_eq!(GaussianInteger::from_str("1+i").unwrap().is_unit(), false);
32    /// assert_eq!(GaussianInteger::TWO.is_unit(), false);
33    /// ```
34    fn is_unit(&self) -> bool {
35        if self.imaginary == 0u32 {
36            self.real == 1u32 || self.real == -1i32
37        } else if self.real == 0u32 {
38            self.imaginary == 1u32 || self.imaginary == -1i32
39        } else {
40            false
41        }
42    }
43}