use crate::Rational;
use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use malachite_base::num::arithmetic::traits::{Abs, AbsAssign, Floor, UnsignedAbs};
use malachite_base::num::conversion::traits::PowerOf2Digits;
use malachite_base::rational_sequences::RationalSequence;
use malachite_nz::natural::Natural;
pub(crate) fn to_power_of_2_digits_helper(
x: Rational,
log_base: u64,
) -> (Vec<Natural>, RationalSequence<Natural>) {
let floor = (&x).floor();
let mut remainder = x - Rational::from(&floor);
let before_point = floor.unsigned_abs().to_power_of_2_digits_asc(log_base);
let mut state_map = BTreeMap::new();
let mut digits = Vec::new();
for i in 0.. {
if remainder == 0u32 {
return (before_point, RationalSequence::from_vec(digits));
}
if let Some(previous_i) = state_map.insert(remainder.clone(), i) {
let repeating = digits.drain(previous_i..).collect();
return (before_point, RationalSequence::from_vecs(digits, repeating));
}
remainder <<= log_base;
let floor = (&remainder).floor().unsigned_abs();
digits.push(floor.clone());
remainder -= Rational::from(floor);
}
unreachable!()
}
impl Rational {
#[inline]
pub fn into_power_of_2_digits(
mut self,
log_base: u64,
) -> (Vec<Natural>, RationalSequence<Natural>) {
self.abs_assign();
to_power_of_2_digits_helper(self, log_base)
}
pub fn to_power_of_2_digits(&self, log_base: u64) -> (Vec<Natural>, RationalSequence<Natural>) {
to_power_of_2_digits_helper(self.abs(), log_base)
}
}