I wrote this algorithm for adding two numbers with unlimited length:
fn add(self, rhs: Self) -> Self::Output {
let mut data = self.data;
let mut other_data = rhs.data;
let mut error = 0;
if data.len() > other_data.len() {
error = data.len() - other_data.len();
other_data.append(&mut vec![0; error]);
} else if data.len() < other_data.len() {
error = other_data.len() - data.len();
data.append(&mut vec![0; error]);
}
assert!(data.len() == other_data.len());
let mut carry_flag: u16 = 0;
let mut set_on_last = false;
for (idx, other_data) in other_data.iter().enumerate() {
let add_res = *other_data as u16 + data[idx] as u16 + carry_flag;
if add_res > u8::MAX as u16 {
carry_flag = add_res / u8::MAX as u16;
data[idx] = (add_res as u16 % u8::MAX as u16) as u8;
set_on_last = true;
} else {
data[idx] = add_res as u8;
set_on_last = false;
}
}
if set_on_last {
for (idx, data_) in data.clone().iter().rev().enumerate() {
if data_ == &0 {
data.remove(idx);
}
}
data.push(carry_flag as u8);
}
Self {data, polarity: true}
}
However, when I try and add two numbers (45986093450806083945+938650409348560983), I get 1334440654591915589918089391908436672 back from the program. The function takes in two Vec<u8>
and tries to add them together. What is the issue with the algorithm? is there a simpler way to do this?