malachite_base/num/factorization/typst.rs
1// Copyright © 2026 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::num::basic::unsigneds::PrimitiveUnsigned;
10use crate::num::factorization::factor::Factors;
11use crate::strings::typst::ToTypst;
12use core::fmt::{Display, Formatter, Result, Write};
13
14impl<T: PrimitiveUnsigned, const N: usize> ToTypst for Factors<T, N> {
15 /// Writes a [`Factors`] as a Typst math-mode fragment.
16 ///
17 /// The fragment is the factorization written out as a product of prime powers, so the
18 /// factorization of 90 becomes `2 times 3^2 times 5`. An exponent of 1 is left off, as it is
19 /// when a factorization is written by hand.
20 ///
21 /// The factorization of 1 has no factors at all, and becomes `1`: the empty product, which is
22 /// what it multiplies out to.
23 ///
24 /// # Worst-case complexity
25 /// $T(n) = O(n)$
26 ///
27 /// $M(n) = O(1)$
28 ///
29 /// where $T$ is time, $M$ is additional memory, and $n$ is the number of distinct prime
30 /// factors.
31 ///
32 /// # Examples
33 /// ```
34 /// use malachite_base::num::factorization::traits::Factor;
35 /// use malachite_base::strings::typst::ToTypst;
36 ///
37 /// assert_eq!(1u32.factor().to_typst_string(), "1");
38 /// assert_eq!(2u32.factor().to_typst_string(), "2");
39 /// assert_eq!(4u32.factor().to_typst_string(), "2^2");
40 /// assert_eq!(90u32.factor().to_typst_string(), "2 times 3^2 times 5");
41 /// assert_eq!(1024u32.factor().to_typst_string(), "2^(10)");
42 /// ```
43 ///
44 /// | value | fragment |
45 /// |--------------------|-----------------------|
46 /// | `1u32.factor()` | `1` |
47 /// | `2u32.factor()` | `2` |
48 /// | `4u32.factor()` | `2^2` |
49 /// | `90u32.factor()` | `2 times 3^2 times 5` |
50 /// | `1024u32.factor()` | `2^(10)` |
51 fn fmt_typst(&self, f: &mut Formatter) -> Result {
52 let mut any = false;
53 for (factor, exponent) in self.clone() {
54 if any {
55 f.write_str(" times ")?;
56 }
57 any = true;
58 Display::fmt(&factor, f)?;
59 if exponent != 1 {
60 f.write_char('^')?;
61 // A lone digit needs no grouping, and an exponent of 1 is never written.
62 if exponent < 10 {
63 Display::fmt(&exponent, f)?;
64 } else {
65 f.write_char('(')?;
66 Display::fmt(&exponent, f)?;
67 f.write_char(')')?;
68 }
69 }
70 }
71 if any {
72 Ok(())
73 } else {
74 // The factorization of 1 is the empty product.
75 f.write_char('1')
76 }
77 }
78}