malachite_base/num/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::num::arithmetic::traits::{DivisibleByPowerOf2, ModPowerOf2};
10use crate::num::conversion::traits::WrappingFrom;
11
12macro_rules! impl_divisible_by_power_of_2_unsigned {
13    ($t:ident) => {
14        impl DivisibleByPowerOf2 for $t {
15            /// Returns whether a number is divisible by $2^k$.
16            ///
17            /// $f(x, k) = (2^k|x)$.
18            ///
19            /// $f(x, k) = (\exists n \in \N : \ x = n2^k)$.
20            ///
21            /// # Worst-case complexity
22            /// Constant time and additional memory.
23            ///
24            /// # Examples
25            /// See [here](super::divisible_by_power_of_2#divisible_by_power_of_2).
26            #[inline]
27            fn divisible_by_power_of_2(self, pow: u64) -> bool {
28                self.mod_power_of_2(pow) == 0
29            }
30        }
31    };
32}
33apply_to_unsigneds!(impl_divisible_by_power_of_2_unsigned);
34
35macro_rules! impl_divisible_by_power_of_2_signed {
36    ($u:ident, $s:ident) => {
37        impl DivisibleByPowerOf2 for $s {
38            /// Returns whether a number is divisible by $2^k$.
39            ///
40            /// $f(x, k) = (2^k|x)$.
41            ///
42            /// $f(x, k) = (\exists n \in \N : x = n2^k)$.
43            ///
44            /// # Worst-case complexity
45            /// Constant time and additional memory.
46            ///
47            /// # Examples
48            /// See [here](super::divisible_by_power_of_2#divisible_by_power_of_2).
49            #[inline]
50            fn divisible_by_power_of_2(self, pow: u64) -> bool {
51                $u::wrapping_from(self).divisible_by_power_of_2(pow)
52            }
53        }
54    };
55}
56apply_to_unsigned_signed_pairs!(impl_divisible_by_power_of_2_signed);