Skip to main content

malachite_nz/natural/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::natural::InnerNatural::{Large, Small};
10use crate::natural::Natural;
11use crate::platform::Limb;
12use malachite_base::num::arithmetic::traits::IsPowerOf2;
13use malachite_base::slices::slice_test_zero;
14
15// Interpreting a slice of `Limb`s as the limbs of a `Natural` in ascending order, determines
16// whether that `Natural` is an integer power of 2.
17//
18// This function assumes that `xs` is nonempty and the last (most significant) limb is nonzero.
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 `xs.len()`.
26//
27// # Panics
28// Panics if `xs` is empty.
29pub_crate_test! {limbs_is_power_of_2(xs: &[Limb]) -> bool {
30    let (xs_last, xs_init) = xs.split_last().unwrap();
31    slice_test_zero(xs_init) && xs_last.is_power_of_2()
32}}
33
34impl IsPowerOf2 for Natural {
35    /// Determines whether a [`Natural`] is an integer power of 2.
36    ///
37    /// $f(x) = (\exists n \in \Z : 2^n = x)$.
38    ///
39    /// # Worst-case complexity
40    /// $T(n) = O(n)$
41    ///
42    /// $M(n) = O(1)$
43    ///
44    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
45    ///
46    /// # Examples
47    /// ```
48    /// use core::str::FromStr;
49    /// use malachite_base::num::arithmetic::traits::{IsPowerOf2, Pow};
50    /// use malachite_base::num::basic::traits::Zero;
51    /// use malachite_nz::natural::Natural;
52    ///
53    /// assert_eq!(Natural::ZERO.is_power_of_2(), false);
54    /// assert_eq!(Natural::from(123u32).is_power_of_2(), false);
55    /// assert_eq!(Natural::from(0x80u32).is_power_of_2(), true);
56    /// assert_eq!(Natural::from(10u32).pow(12).is_power_of_2(), false);
57    /// assert_eq!(
58    ///     Natural::from_str("1099511627776").unwrap().is_power_of_2(),
59    ///     true
60    /// );
61    /// ```
62    fn is_power_of_2(&self) -> bool {
63        match self {
64            Self(Small(small)) => small.is_power_of_2(),
65            Self(Large(limbs)) => limbs_is_power_of_2(limbs),
66        }
67    }
68}