From 00856e19b215222176cf0cb9c83fd880846c2c0f Mon Sep 17 00:00:00 2001 From: Andrew Guschin Date: Fri, 21 Apr 2023 09:42:07 +0400 Subject: =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B0?= =?UTF-8?q?=20=D1=80=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=B0=D0=BB=D0=B3=D0=BE=D1=80=D0=B8=D1=82=D0=BC=D0=B0=20?= =?UTF-8?q?=D0=BD=D0=B0=D1=85=D0=BE=D0=B6=D0=B4=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D1=8D=D0=BB=D0=B5=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=20g=20=D0=BF?= =?UTF-8?q?=D0=BE=D1=80=D1=8F=D0=B4=D0=BA=D0=B0=20q=20=D0=B2=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BD=D0=B5=D1=87=D0=BD=D0=BE=D0=BC=20=D0=BF=D0=BE=D0=BB?= =?UTF-8?q?=D0=B5=20Z=5Fp.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sem2/src/mpn.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) (limited to 'sem2/src/mpn.rs') diff --git a/sem2/src/mpn.rs b/sem2/src/mpn.rs index 91d3ff8..cb95e7f 100644 --- a/sem2/src/mpn.rs +++ b/sem2/src/mpn.rs @@ -1,11 +1,12 @@ +use fastrand; use std::cmp::{max, Ordering}; use std::fmt; use std::ops::{Add, Div, Index, IndexMut, Mul, Rem, Sub}; #[derive(Debug)] pub struct Number { - radix: u8, - digits: Vec, + pub radix: u8, + pub digits: Vec, } impl Clone for Number { @@ -81,6 +82,27 @@ impl Number { return true; } + pub fn random_below(&self) -> Number { + loop { + let num = Number::random_num(self.len(), self.radix); + if num < self.clone() { + return num; + } + } + } + + pub fn random_num(size: usize, radix: u8) -> Number { + let mut digits = Vec::new(); + for _ in 0..size - 1 { + digits.push(fastrand::u8(..radix)); + } + digits.push(fastrand::u8(1..radix)); + + return Number::from_digits(&digits, radix).unwrap(); + } +} + +impl Number { fn parse_digit(c: u8) -> Option { if c >= 'a' as u8 { Some(c - 'a' as u8 + 10_u8) @@ -107,6 +129,26 @@ impl Number { } } +impl From for Number { + fn from(mut num: u64) -> Self { + let radix = 10; + let mut digits = Vec::new(); + while num != 0 { + let digit = num % radix; + num /= radix; + digits.push(digit as u8); + } + if digits.len() == 0 { + digits.push(0); + } + return Number { + radix: radix as u8, + digits, + } + .fix_leading_zeros(); + } +} + impl fmt::Display for Number { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for i in (0..self.digits.len()).rev() { -- cgit v1.2.3