Mul seems to be working

This commit is contained in:
Fabian Schmidt 2024-11-26 11:11:08 +01:00
parent 23a96d5bee
commit 2ec7e6c296

View File

@ -7,42 +7,43 @@ impl Mul for Number {
#[allow(clippy::suspicious_arithmetic_impl)] #[allow(clippy::suspicious_arithmetic_impl)]
fn mul(self, rhs: Self) -> Self::Output { fn mul(self, rhs: Self) -> Self::Output {
println!("left {self:#?}");
println!("right {rhs:#?}");
let mut mult_vecs = Vec::new();
let sign = match (self.sign, rhs.sign) { let sign = match (self.sign, rhs.sign) {
(Sign::Positif, Sign::Positif) => Sign::Positif, (Sign::Positif, Sign::Positif) => Sign::Positif,
(Sign::Positif, Sign::Negatif) => Sign::Negatif, (Sign::Positif, Sign::Negatif) => Sign::Negatif,
(Sign::Negatif, Sign::Positif) => Sign::Negatif, (Sign::Negatif, Sign::Positif) => Sign::Negatif,
(Sign::Negatif, Sign::Negatif) => Sign::Positif, (Sign::Negatif, Sign::Negatif) => Sign::Positif,
}; };
for (idx, rdigit) in rhs.digits.iter().enumerate() { let mut digits = Vec::new();
let rdigit = rdigit * 10_isize.pow(idx as u32); for (zeroes, rdigit) in rhs.digits.iter().enumerate() {
let mult_vec: Vec<isize> = self.digits.iter().map(|ldigit| ldigit * rdigit).collect(); for (idx, ldigit) in self.digits.iter().enumerate() {
let mut normalized_mult_vec = Vec::new(); let mult = rdigit * ldigit;
let mut carry = 0; let new = mult % 10;
let mut add_zero = true; let mut carry = mult / 10;
mult_vec.into_iter().for_each(|digit| { if let Some(old) = digits.get(zeroes + idx) {
let digit = digit + carry; let add = old + new;
if digit > 9 { digits[zeroes + idx] = add % 10;
carry = digit % 10; carry += add / 10;
normalized_mult_vec.insert(0, digit / 10);
} else { } else {
normalized_mult_vec.insert(0, digit); digits.push(new);
carry = 0; }
add_zero = false; let mut carry_idx = 1;
loop {
if carry == 0 {
break;
}
if let Some(old) = digits.get(zeroes + idx + carry_idx) {
let add = old + carry;
digits[zeroes + idx + carry_idx] = add % 10;
carry = add / 10;
} else {
digits.push(carry % 10);
carry /= 10;
}
carry_idx += 1;
} }
});
if carry != 0 || add_zero {
normalized_mult_vec.insert(0, carry);
} }
mult_vecs.push(Number {
digits: normalized_mult_vec,
sign,
});
} }
Number { digits, sign }
mult_vecs.into_iter().reduce(|acc, num| acc + num).unwrap()
} }
} }
@ -123,7 +124,15 @@ mod test_number_mul {
} }
#[test] #[test]
fn mul_big() { fn mul_big_1() {
let a = Number::from("123");
let b = Number::from("321");
let res = Number::from("39483");
assert_eq!(res, a * b);
}
#[test]
fn mul_big_2() {
let a = Number::from("123456789"); let a = Number::from("123456789");
let b = Number::from("987654321"); let b = Number::from("987654321");
let res = Number::from("121932631112635269"); let res = Number::from("121932631112635269");