diff options
| author | Andrew Guschin <guschin.drew@gmail.com> | 2023-03-17 21:03:19 +0400 |
|---|---|---|
| committer | Andrew Guschin <guschin.drew@gmail.com> | 2023-03-17 21:03:19 +0400 |
| commit | 3afa13a155c3bc9101f39e4e4f209b65e5ebc88e (patch) | |
| tree | 84440d0c3f5dc5b2911bf5c49ea2b98124bbdce3 | |
| parent | 0a3330a6959405913fdd14516e72a587ce6eefc6 (diff) | |
Добавлена проверка на 0
| -rw-r--r-- | sem2/src/main.rs | 16 | ||||
| -rw-r--r-- | sem2/src/mpn.rs | 37 |
2 files changed, 40 insertions, 13 deletions
diff --git a/sem2/src/main.rs b/sem2/src/main.rs index d2c7376..b190a96 100644 --- a/sem2/src/main.rs +++ b/sem2/src/main.rs @@ -67,11 +67,21 @@ fn main() { let mpn_elapsed = mpn_start.elapsed(); let rug_start = Instant::now(); - let _rug_res = a_rug.div_rem(b_rug); + if let Ok(_) = &mpn_res { + let _rug_res = a_rug.div_rem(b_rug); + } let rug_elapsed = rug_start.elapsed(); - println!("Частное: {}", mpn_res.0); - println!("Остаток: {}", mpn_res.1); + match mpn_res { + Ok((div, rem)) => { + println!("Частное: {}", div); + println!("Остаток: {}", rem); + } + Err(msg) => { + println!("{msg}"); + return; + } + } println!( "Операция произведения выполнена в mpn за {} наносекунд", diff --git a/sem2/src/mpn.rs b/sem2/src/mpn.rs index caccc33..1cd0383 100644 --- a/sem2/src/mpn.rs +++ b/sem2/src/mpn.rs @@ -41,6 +41,15 @@ impl Number { self.digits.len() } + pub fn is_zero(&self) -> bool { + for i in &self.digits { + if *i != 0 { + return false; + } + } + return true; + } + fn parse_digit(c: u8) -> Option<u8> { if c >= 'a' as u8 { Some(c - 'a' as u8 + 10_u8) @@ -185,15 +194,19 @@ impl Mul for Number { } impl Number { - pub fn div_rem(self, other: Self) -> (Self, Self) { + pub fn div_rem(self, other: Self) -> Result<(Self, Self), String> { + if other.is_zero() { + return Err("Деление на 0 запрещено".to_string()); + } + if self < other { - return ( + return Ok(( Number { radix: self.radix, digits: vec![0], }, self, - ); + )); } fn div_digit(a: &Vec<u8>, b: u8, radix: u8) -> (Vec<u8>, u8) { @@ -210,7 +223,7 @@ impl Number { if other.len() == 1 { let (div, rem) = div_digit(&self.digits, other.digits[0], self.radix as u8); - return ( + return Ok(( Number { radix: self.radix, digits: div, @@ -221,7 +234,7 @@ impl Number { digits: vec![rem], } .fix_leading_zeros(), - ); + )); } fn mul_digit(a: &Vec<u8>, b: u8, radix: u8) -> Vec<u8> { @@ -300,7 +313,7 @@ impl Number { } .fix_leading_zeros(); - return (div, rem); + return Ok((div, rem)); } } @@ -308,8 +321,10 @@ impl Div for Number { type Output = Self; fn div(self, other: Self) -> Self::Output { - let (div, _) = self.div_rem(other); - return div; + match self.div_rem(other) { + Ok((div, _)) => div, + Err(msg) => panic!("{msg}"), + } } } @@ -317,8 +332,10 @@ impl Rem for Number { type Output = Self; fn rem(self, other: Self) -> Self::Output { - let (_, rem) = self.div_rem(other); - return rem; + match self.div_rem(other) { + Ok((_, rem)) => rem, + Err(msg) => panic!("{msg}"), + } } } |