Skip to main content

malachite_nz/gaussian_integer/arithmetic/
is_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::gaussian_integer::GaussianInteger;
10use malachite_base::num::arithmetic::traits::IsPowerOf2;
11
12impl IsPowerOf2 for GaussianInteger {
13    /// Determines whether a [`GaussianInteger`] is an integer power of 2.
14    ///
15    /// Only purely real, positive values qualify; in particular, $i$ and its multiples are not
16    /// powers of 2.
17    ///
18    /// $f(x) = (\exists n \in \N : 2^n = x)$.
19    ///
20    /// # Worst-case complexity
21    /// $T(n) = O(n)$
22    ///
23    /// $M(n) = O(1)$
24    ///
25    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.real.significant_bits()`.
26    ///
27    /// # Examples
28    /// ```
29    /// use malachite_base::num::arithmetic::traits::IsPowerOf2;
30    /// use malachite_nz::gaussian_integer::GaussianInteger;
31    /// use std::str::FromStr;
32    ///
33    /// assert_eq!(GaussianInteger::from(0x80).is_power_of_2(), true);
34    /// assert_eq!(GaussianInteger::from(-0x80).is_power_of_2(), false);
35    /// assert_eq!(GaussianInteger::from(0x81).is_power_of_2(), false);
36    /// assert_eq!(
37    ///     GaussianInteger::from_str("128i").unwrap().is_power_of_2(),
38    ///     false
39    /// );
40    /// assert_eq!(
41    ///     GaussianInteger::from_str("128+i").unwrap().is_power_of_2(),
42    ///     false
43    /// );
44    /// ```
45    #[inline]
46    fn is_power_of_2(&self) -> bool {
47        self.imaginary == 0u32 && self.real.is_power_of_2()
48    }
49}