malachite_nz/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::integer::Integer;
10use malachite_base::num::arithmetic::traits::IsPowerOf2;
11
12impl IsPowerOf2 for Integer {
13 /// Determines whether an [`Integer`] is an integer power of 2.
14 ///
15 /// Negative values are never powers of 2.
16 ///
17 /// $f(x) = (\exists n \in \N : 2^n = x)$.
18 ///
19 /// # Worst-case complexity
20 /// $T(n) = O(n)$
21 ///
22 /// $M(n) = O(1)$
23 ///
24 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
25 ///
26 /// # Examples
27 /// ```
28 /// use core::str::FromStr;
29 /// use malachite_base::num::arithmetic::traits::{IsPowerOf2, Pow};
30 /// use malachite_base::num::basic::traits::Zero;
31 /// use malachite_nz::integer::Integer;
32 ///
33 /// assert_eq!(Integer::ZERO.is_power_of_2(), false);
34 /// assert_eq!(Integer::from(123).is_power_of_2(), false);
35 /// assert_eq!(Integer::from(0x80).is_power_of_2(), true);
36 /// assert_eq!(Integer::from(-0x80).is_power_of_2(), false);
37 /// assert_eq!(Integer::from(10).pow(12).is_power_of_2(), false);
38 /// assert_eq!(
39 /// Integer::from_str("1099511627776").unwrap().is_power_of_2(),
40 /// true
41 /// );
42 /// ```
43 #[inline]
44 fn is_power_of_2(&self) -> bool {
45 self.sign && self.abs.is_power_of_2()
46 }
47}