malachite_q/conversion/digits/power_of_2_digits.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 alloc::vec::Vec;
11use malachite_base::num::arithmetic::traits::{Abs, Floor, UnsignedAbs};
12use malachite_base::num::conversion::traits::PowerOf2Digits;
13use malachite_nz::natural::Natural;
14
15/// Represents the base-$2^k$ digits of the fractional portion of a [`Rational`] number.
16///
17/// See [`power_of_2_digits`](Rational::power_of_2_digits) for more information.
18#[derive(Clone, Debug, Eq, PartialEq)]
19pub struct RationalPowerOf2Digits {
20 log_base: u64,
21 remainder: Rational,
22}
23
24impl Iterator for RationalPowerOf2Digits {
25 type Item = Natural;
26
27 fn next(&mut self) -> Option<Natural> {
28 if self.remainder == 0u32 {
29 None
30 } else {
31 self.remainder <<= self.log_base;
32 let digit = (&self.remainder).floor().unsigned_abs();
33 self.remainder -= Rational::from(&digit);
34 Some(digit)
35 }
36 }
37}
38
39impl Rational {
40 /// Returns the base-$2^k$ digits of a [`Rational`].
41 ///
42 /// The output has two components. The first is a [`Vec`] of the digits of the integer portion
43 /// of the [`Rational`], least- to most-significant. The second is an iterator of the digits of
44 /// the fractional portion.
45 ///
46 /// The output is in its simplest form: the integer-portion digits do not end with a zero, and
47 /// the fractional-portion digits do not end with infinitely many zeros or $(2^k-1)$s.
48 ///
49 /// If the [`Rational`] has a small denominator, it may be more efficient to use
50 /// [`to_power_of_2_digits`](Rational::to_power_of_2_digits) or
51 /// [`into_power_of_2_digits`](Rational::into_power_of_2_digits) instead. These functions
52 /// compute the entire repeating portion of the repeating digits.
53 ///
54 /// For example, consider these two expressions:
55 /// - `Rational::from_signeds(1, 7).power_of_2_digits(1).1.nth(1000)`
56 /// - `Rational::from_signeds(1, 7).into_power_of_2_digits(1).1[1000]`
57 ///
58 /// Both get the thousandth digit after the binary point of `1/7`. The first way explicitly
59 /// calculates each bit after the binary point, whereas the second way determines that `1/7` is
60 /// `0.(001)`, with the `001` repeating, and takes `1000 % 3 == 1` to determine that the
61 /// thousandth bit is 0. But when the [`Rational`] has a large denominator, the second way is
62 /// less efficient.
63 ///
64 /// # Worst-case complexity per iteration
65 /// $T(n) = O(n \log n \log\log n)$
66 ///
67 /// $M(n) = O(n \log n)$
68 ///
69 /// where $T$ is time, $M$ is additional memory, and $n$ is `max(self.significant_bits(),
70 /// base)`.
71 ///
72 /// # Panics
73 /// Panics if `log_base` is zero.
74 ///
75 /// # Examples
76 /// ```
77 /// use malachite_base::iterators::prefix_to_string;
78 /// use malachite_base::strings::ToDebugString;
79 /// use malachite_q::Rational;
80 ///
81 /// let (before_point, after_point) = Rational::from(3u32).power_of_2_digits(1);
82 /// assert_eq!(before_point.to_debug_string(), "[1, 1]");
83 /// assert_eq!(prefix_to_string(after_point, 10), "[]");
84 ///
85 /// let (before_point, after_point) = Rational::from_signeds(22, 7).power_of_2_digits(1);
86 /// assert_eq!(before_point.to_debug_string(), "[1, 1]");
87 /// assert_eq!(
88 /// prefix_to_string(after_point, 10),
89 /// "[0, 0, 1, 0, 0, 1, 0, 0, 1, 0, ...]"
90 /// );
91 ///
92 /// let (before_point, after_point) = Rational::from_signeds(22, 7).power_of_2_digits(10);
93 /// assert_eq!(before_point.to_debug_string(), "[3]");
94 /// assert_eq!(
95 /// prefix_to_string(after_point, 10),
96 /// "[146, 292, 585, 146, 292, 585, 146, 292, 585, 146, ...]"
97 /// );
98 /// ```
99 pub fn power_of_2_digits(&self, log_base: u64) -> (Vec<Natural>, RationalPowerOf2Digits) {
100 let mut remainder = self.abs();
101 let floor = (&remainder).floor().unsigned_abs();
102 remainder -= Self::from(&floor);
103 (
104 floor.to_power_of_2_digits_asc(log_base),
105 RationalPowerOf2Digits {
106 log_base,
107 remainder,
108 },
109 )
110 }
111}