1use factorion_math::rug::ops::AddFrom;
4#[cfg(any(feature = "serde", test))]
5use serde::{Deserialize, Serialize};
6
7use crate::calculation_results::Number;
8
9use crate::Consts;
10use crate::{
11 calculation_results::{Calculation, CalculationResult},
12 math,
13};
14
15use crate::rug::{Float, ops::Pow};
16
17pub mod recommended {
18 use factorion_math::rug::Complete;
19 use factorion_math::rug::integer::IntegerExt64;
20
21 use crate::rug::Integer;
22 pub static UPPER_CALCULATION_LIMIT: fn() -> Integer = || 1_000_000.into();
24 pub static UPPER_APPROXIMATION_LIMIT: fn() -> Integer =
26 || Integer::u64_pow_u64(10, 300).complete();
27 pub static UPPER_SUBFACTORIAL_LIMIT: fn() -> Integer = || 100_000.into();
29 pub static UPPER_TERMIAL_LIMIT: fn() -> Integer = || Integer::u64_pow_u64(10, 10000).complete();
31 pub static UPPER_TERMIAL_APPROXIMATION_LIMIT: u32 = 1073741822;
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
38#[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))]
39pub struct CalculationJob {
40 pub base: CalculationBase,
41 pub level: i32,
43 pub negative: u32,
45}
46#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
48#[cfg_attr(any(feature = "serde", test), derive(Serialize, Deserialize))]
49pub enum CalculationBase {
50 Num(Number),
51 Calc(Box<CalculationJob>),
52}
53
54impl CalculationJob {
55 pub fn execute(self, include_steps: bool, consts: &Consts) -> Vec<Option<Calculation>> {
58 let CalculationJob {
59 mut base,
60 mut level,
61 mut negative,
62 } = self;
63 let size = {
64 let mut n = 1;
65 let mut b = &base;
66 while let CalculationBase::Calc(inner) = b {
67 n += 1;
68 b = &inner.base;
69 }
70 n
71 };
72 let mut steps = Vec::with_capacity(size);
74 let mut calcs = loop {
75 match base {
76 CalculationBase::Num(num) => {
77 break vec![
78 Self::calculate_appropriate_factorial(num.clone(), level, negative, consts)
79 .map(|res| Calculation {
80 value: num,
81 steps: vec![(level, negative % 2 == 1)],
82 result: res,
83 }),
84 ];
85 }
86 CalculationBase::Calc(calc) => {
87 steps.push((level, negative));
88 CalculationJob {
89 base,
90 level,
91 negative,
92 } = *calc;
93 }
94 }
95 };
96 for (i, (level, negative)) in steps.into_iter().rev().enumerate() {
97 let calc = if include_steps && i < 30 {
98 calcs.last().cloned()
99 } else {
100 calcs.pop()
101 };
102 match calc {
103 Some(Some(Calculation {
104 result: res,
105 mut steps,
106 value: number,
107 })) => {
108 let factorial = Self::calculate_appropriate_factorial(
109 res, level, negative, consts,
110 )
111 .map(|res| {
112 steps.push((level, negative % 2 == 1));
113 Calculation {
114 value: number,
115 steps,
116 result: res,
117 }
118 });
119 calcs.push(factorial);
120 }
121 _ => return calcs,
122 };
123 }
124 calcs
125 }
126 fn calculate_appropriate_factorial(
127 num: Number,
128 level: i32,
129 negative: u32,
130 consts: &Consts,
131 ) -> Option<CalculationResult> {
132 let prec = consts.float_precision;
133 let calc_num = match num {
134 CalculationResult::Approximate(base, exponent) => {
135 if exponent <= consts.integer_construction_limit {
136 let x: Float = base.as_float() * Float::with_val(prec, 10).pow(&exponent);
137 x.to_integer().unwrap()
138 } else {
139 return Some(if base.as_float() < &0.0 {
140 CalculationResult::ComplexInfinity
141 } else if level < 0 {
142 let termial = math::approximate_approx_termial(
143 (Float::from(base), exponent),
144 -level as u32,
145 );
146 if termial.0 == 1 {
147 CalculationResult::ApproximateDigits(false, termial.1)
148 } else {
149 CalculationResult::Approximate(termial.0.into(), termial.1)
150 }
151 } else {
152 let mut exponent = exponent;
153 exponent.add_from(math::length(&exponent, prec));
154 CalculationResult::ApproximateDigitsTower(false, false, 1.into(), exponent)
155 });
156 }
157 }
158 CalculationResult::ApproximateDigits(was_neg, digits) => {
159 if digits <= consts.integer_construction_limit {
160 let x: Float = Float::with_val(prec, 10).pow(digits.clone() - 1);
161 x.to_integer().unwrap()
162 } else {
163 return Some(if digits.is_negative() {
164 CalculationResult::Float(Float::new(prec).into())
165 } else if was_neg {
166 CalculationResult::ComplexInfinity
167 } else if level < 0 {
168 let mut one = Float::with_val(consts.float_precision, 1);
169 if was_neg {
170 one *= -1;
171 }
172 let termial =
173 math::approximate_approx_termial((one, digits), -level as u32);
174 if termial.0 == 1 {
175 CalculationResult::ApproximateDigits(false, termial.1)
176 } else {
177 CalculationResult::Approximate(termial.0.into(), termial.1)
178 }
179 } else {
180 let mut digits = digits;
181 digits.add_from(math::length(&digits, prec));
182 CalculationResult::ApproximateDigitsTower(false, false, 1.into(), digits)
183 });
184 }
185 }
186 CalculationResult::ApproximateDigitsTower(was_neg, neg, depth, exponent) => {
187 return Some(if neg {
188 CalculationResult::Float(Float::new(prec).into())
189 } else if was_neg {
190 CalculationResult::ComplexInfinity
191 } else if level < 0 {
192 CalculationResult::ApproximateDigitsTower(false, false, depth, exponent)
193 } else {
194 CalculationResult::ApproximateDigitsTower(false, false, depth + 1, exponent)
195 });
196 }
197 CalculationResult::ComplexInfinity => return Some(CalculationResult::ComplexInfinity),
198 Number::Float(num) => match level {
199 ..-1 => {
200 return None;
202 }
203 -1 => {
204 let res: Float = math::fractional_termial(num.as_float().clone())
205 * if negative % 2 != 0 { -1 } else { 1 };
206 if res.is_finite() {
207 return Some(CalculationResult::Float(res.into()));
208 } else {
209 num.as_float().to_integer()?
210 }
211 }
212 0 => {
213 return None;
215 }
216 1 => {
217 let res: Float = math::fractional_factorial(num.as_float().clone())
218 * if negative % 2 != 0 { -1 } else { 1 };
219 if res.is_finite() {
220 return Some(CalculationResult::Float(res.into()));
221 } else {
222 num.as_float().to_integer()?
223 }
224 }
225 2.. => {
226 let res: Float =
227 math::fractional_multifactorial(num.as_float().clone(), level as u32)
228 * if negative % 2 != 0 { -1 } else { 1 };
229 if res.is_finite() {
230 return Some(CalculationResult::Float(res.into()));
231 } else {
232 num.as_float().to_integer()?
233 }
234 }
235 },
236 Number::Exact(num) => num,
237 };
238 if level > 0 {
239 Some(if calc_num < 0 && level == 1 {
240 CalculationResult::ComplexInfinity
241 } else if calc_num < 0 {
242 let factor = math::negative_multifacorial_factor(calc_num.clone(), level);
243 match (factor, -level - 1 > calc_num) {
244 (Some(factor), true) => {
245 let mut res = Self::calculate_appropriate_factorial(
246 Number::Exact(-calc_num.clone() - level),
247 level,
248 negative,
249 consts,
250 )?;
251 res = match res {
252 CalculationResult::Exact(n) => {
253 let n = Float::with_val(prec, n);
254 CalculationResult::Float((factor / n).into())
255 }
256 CalculationResult::Approximate(b, e) => {
257 let (b, e) =
258 math::adjust_approximate((factor / Float::from(b), -e));
259 CalculationResult::Approximate(b.into(), e)
260 }
261 CalculationResult::ApproximateDigits(wn, n) => {
262 CalculationResult::ApproximateDigits(wn, -n)
263 }
264 CalculationResult::ApproximateDigitsTower(
265 wn,
266 negative,
267 depth,
268 base,
269 ) => CalculationResult::ApproximateDigitsTower(
270 wn, !negative, depth, base,
271 ),
272 CalculationResult::ComplexInfinity => {
273 CalculationResult::Exact(0.into())
274 }
275 CalculationResult::Float(f) => {
276 CalculationResult::Float((factor / Float::from(f)).into())
277 }
278 };
279
280 res
281 }
282 (factor, _) => factor
283 .map(CalculationResult::Exact)
284 .unwrap_or(CalculationResult::ComplexInfinity),
285 }
286 } else if calc_num > consts.upper_approximation_limit {
288 let factorial =
289 math::approximate_multifactorial_digits(calc_num.clone(), level as u32, prec);
290 CalculationResult::ApproximateDigits(negative % 2 != 0, factorial)
291 } else if calc_num > consts.upper_calculation_limit {
293 let factorial = if level == 0 {
294 math::approximate_factorial(calc_num.clone(), prec)
295 } else {
296 math::approximate_multifactorial(calc_num.clone(), level as u32, prec)
297 };
298 CalculationResult::Approximate(
299 ((factorial.0 * if negative % 2 != 0 { -1 } else { 1 }) as Float).into(),
300 factorial.1,
301 )
302 } else {
303 let calc_num = calc_num
304 .to_u64()
305 .unwrap_or_else(|| panic!("Failed to convert BigInt to u64: {calc_num}"));
306 let factorial = math::factorial(calc_num, level as u32)
307 * if negative % 2 != 0 { -1 } else { 1 };
308 CalculationResult::Exact(factorial)
309 })
310 } else if level == 0 {
311 Some(if calc_num < 0 {
312 CalculationResult::ComplexInfinity
313 } else if calc_num > consts.upper_approximation_limit {
314 let factorial = math::approximate_multifactorial_digits(calc_num.clone(), 1, prec);
315 CalculationResult::ApproximateDigits(negative % 2 != 0, factorial)
316 } else if calc_num > consts.upper_subfactorial_limit {
317 let factorial = math::approximate_subfactorial(calc_num.clone(), prec);
318 CalculationResult::Approximate(
319 ((factorial.0 * if negative % 2 != 0 { -1 } else { 1 }) as Float).into(),
320 factorial.1,
321 )
322 } else {
323 let calc_num = calc_num
324 .to_u64()
325 .unwrap_or_else(|| panic!("Failed to convert BigInt to u64: {calc_num}"));
326 let factorial =
327 math::subfactorial(calc_num) * if negative % 2 != 0 { -1 } else { 1 };
328 CalculationResult::Exact(factorial)
329 })
330 } else if level < 0 {
331 Some(
332 if calc_num.significant_bits() > consts.upper_termial_approximation_limit {
333 let termial = math::approximate_termial_digits(calc_num, -level as u32, prec);
334 CalculationResult::ApproximateDigits(negative % 2 != 0, termial)
335 } else if calc_num > consts.upper_termial_limit {
336 let termial = math::approximate_termial(calc_num, -level as u32, prec);
337 CalculationResult::Approximate(
338 ((termial.0 * if negative % 2 != 0 { -1 } else { 1 }) as Float).into(),
339 termial.1,
340 )
341 } else {
342 let termial = if level < -1 {
343 math::multitermial(calc_num, -level as u32)
344 } else {
345 math::termial(calc_num)
346 };
347 let termial = termial * if negative % 2 != 0 { -1 } else { 1 };
348 CalculationResult::Exact(termial)
349 },
350 )
351 } else {
352 unreachable!()
353 }
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360 use factorion_math::recommended::FLOAT_PRECISION;
361
362 #[test]
363 fn test_unsupported_calcs() {
364 let consts = Consts::default();
365 let job = CalculationJob {
367 base: CalculationBase::Num(Number::Float(Float::with_val(FLOAT_PRECISION, 1.5).into())),
368 level: 0,
369 negative: 0,
370 };
371 assert_eq!(job.execute(false, &consts), vec![None]);
372 let job = CalculationJob {
374 base: CalculationBase::Num(Number::Float(Float::with_val(FLOAT_PRECISION, 1.5).into())),
375 level: -2,
376 negative: 0,
377 };
378 assert_eq!(job.execute(false, &consts), vec![None]);
379 let job = CalculationJob {
380 base: CalculationBase::Num(Number::Float(Float::with_val(FLOAT_PRECISION, 1.5).into())),
381 level: -51,
382 negative: 0,
383 };
384 assert_eq!(job.execute(false, &consts), vec![None]);
385 }
386}