malachite_q/arithmetic/is_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::Rational;
10use malachite_base::num::arithmetic::traits::IsPowerOf2;
11
12impl IsPowerOf2 for Rational {
13 /// Determines whether a [`Rational`] is an integer power of 2.
14 ///
15 /// $f(x) = (\exists n \in \Z : 2^n = x)$.
16 ///
17 /// # Worst-case complexity
18 /// $T(n) = O(n)$
19 ///
20 /// $M(n) = O(1)$
21 ///
22 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
23 ///
24 /// # Examples
25 /// ```
26 /// use malachite_base::num::arithmetic::traits::IsPowerOf2;
27 /// use malachite_q::Rational;
28 ///
29 /// assert_eq!(Rational::from(0x80).is_power_of_2(), true);
30 /// assert_eq!(Rational::from_signeds(1, 8).is_power_of_2(), true);
31 /// assert_eq!(Rational::from_signeds(-1, 8).is_power_of_2(), false);
32 /// assert_eq!(Rational::from_signeds(22, 7).is_power_of_2(), false);
33 /// ```
34 fn is_power_of_2(&self) -> bool {
35 self.sign
36 && (self.denominator == 1u32 && self.numerator.is_power_of_2()
37 || self.numerator == 1u32 && self.denominator.is_power_of_2())
38 }
39}