malachite_q/arithmetic/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::PowerOf2;
11use malachite_base::num::basic::traits::One;
12use malachite_nz::natural::Natural;
13
14impl PowerOf2<u64> for Rational {
15 /// Raises 2 to an integer power.
16 ///
17 /// $f(k) = 2^k$.
18 ///
19 /// # Worst-case complexity
20 /// $T(n) = O(n)$
21 ///
22 /// $M(n) = O(n)$
23 ///
24 /// where $T$ is time, $M$ is additional memory, and $n$ is `pow`.
25 ///
26 /// # Examples
27 /// ```
28 /// use malachite_base::num::arithmetic::traits::PowerOf2;
29 /// use malachite_q::Rational;
30 ///
31 /// assert_eq!(Rational::power_of_2(0u64), 1);
32 /// assert_eq!(Rational::power_of_2(3u64), 8);
33 /// assert_eq!(
34 /// Rational::power_of_2(100u64).to_string(),
35 /// "1267650600228229401496703205376"
36 /// );
37 /// ```
38 fn power_of_2(pow: u64) -> Self {
39 Self::from(Natural::power_of_2(pow))
40 }
41}
42
43impl PowerOf2<i64> for Rational {
44 /// Raises 2 to an integer power.
45 ///
46 /// $f(k) = 2^k$.
47 ///
48 /// # Worst-case complexity
49 /// $T(n) = O(n)$
50 ///
51 /// $M(n) = O(n)$
52 ///
53 /// where $T$ is time, $M$ is additional memory, and $n$ is `pow.abs()`.
54 ///
55 /// # Examples
56 /// ```
57 /// use malachite_base::num::arithmetic::traits::PowerOf2;
58 /// use malachite_q::Rational;
59 ///
60 /// assert_eq!(Rational::power_of_2(0i64), 1);
61 /// assert_eq!(Rational::power_of_2(3i64), 8);
62 /// assert_eq!(
63 /// Rational::power_of_2(100i64).to_string(),
64 /// "1267650600228229401496703205376"
65 /// );
66 /// assert_eq!(Rational::power_of_2(-3i64).to_string(), "1/8");
67 /// assert_eq!(
68 /// Rational::power_of_2(-100i64).to_string(),
69 /// "1/1267650600228229401496703205376"
70 /// );
71 /// ```
72 fn power_of_2(pow: i64) -> Self {
73 let pow_abs = pow.unsigned_abs();
74 if pow >= 0 {
75 Self::from(Natural::power_of_2(pow_abs))
76 } else {
77 Self {
78 sign: true,
79 numerator: Natural::ONE,
80 denominator: Natural::power_of_2(pow_abs),
81 }
82 }
83 }
84}