vertical_multiplication/steps/
steps.rs1use super::*;
2
3impl Display for MultiplicationSteps {
4 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
5 let max_indent = self.max_digits() + 3;
6 let a = self.lhs.to_str_radix(self.base);
7 let b = self.rhs.to_str_radix(self.base);
8 let r = self.result.to_str_radix(self.base);
9 writeln!(f, "{space}{}", a, space = " ".repeat(max_indent - a.len()))?;
10 writeln!(f, " ×{space}{}", b, space = " ".repeat(max_indent - b.len() - 2))?;
11 writeln!(f, "{}", "-".repeat(max_indent + 1))?;
12 for (i, add) in self.steps.iter().enumerate() {
13 if i == 0 {
14 writeln!(f, "{}", add.pretty_format(max_indent, " = ", self.base))?;
15 }
16 else {
17 writeln!(f, "{}", add.pretty_format(max_indent, " + ", self.base))?;
18 }
19 }
20 writeln!(f, "{}", "-".repeat(max_indent + 1))?;
21 write!(f, " = {result}", result = r)
22 }
23}
24
25impl MultiplicationSteps {
26 pub fn new(a: &BigInt, b: &BigInt) -> MultiplicationSteps {
28 Self { lhs: a.clone(), rhs: b.clone(), steps: vec![], result: a.mul(b), base: 10 }
29 }
30 pub fn with_base(mut self, base: u32) -> Self {
32 assert!(base > 1);
33 self.base = base;
34 self
35 }
36 pub fn push_step(&mut self, step: ShiftAdd) {
38 self.steps.push(step);
39 }
40 pub fn max_digits(&self) -> usize {
42 self.steps.iter().map(|x| x.count_digits(self.base)).max().unwrap_or(0)
43 }
44}