malachite_nz/integer/arithmetic/
divisible_by_power_of_2.rs

1// Copyright © 2025 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::DivisibleByPowerOf2;
11
12impl DivisibleByPowerOf2 for &Integer {
13    /// Returns whether an [`Integer`] is divisible by $2^k$.
14    ///
15    /// $f(x, k) = (2^k|x)$.
16    ///
17    /// $f(x, k) = (\exists n \in \N : \ x = n2^k)$.
18    ///
19    /// If `self` is 0, the result is always true; otherwise, it is equivalent to
20    /// `self.trailing_zeros().unwrap() <= pow`, but more efficient.
21    ///
22    /// # Worst-case complexity
23    /// $T(n) = O(n)$
24    ///
25    /// $M(n) = O(1)$
26    ///
27    /// where $T$ is time, $M$ is additional memory, and $n$ is `min(pow, self.significant_bits())`.
28    ///
29    /// # Examples
30    /// ```
31    /// use malachite_base::num::arithmetic::traits::{DivisibleByPowerOf2, Pow};
32    /// use malachite_base::num::basic::traits::Zero;
33    /// use malachite_nz::integer::Integer;
34    ///
35    /// assert_eq!(Integer::ZERO.divisible_by_power_of_2(100), true);
36    /// assert_eq!(Integer::from(-100).divisible_by_power_of_2(2), true);
37    /// assert_eq!(Integer::from(100u32).divisible_by_power_of_2(3), false);
38    /// assert_eq!(
39    ///     (-Integer::from(10u32).pow(12)).divisible_by_power_of_2(12),
40    ///     true
41    /// );
42    /// assert_eq!(
43    ///     (-Integer::from(10u32).pow(12)).divisible_by_power_of_2(13),
44    ///     false
45    /// );
46    /// ```
47    fn divisible_by_power_of_2(self, pow: u64) -> bool {
48        self.abs.divisible_by_power_of_2(pow)
49    }
50}