From 6ddf0167bf7d8a7a9f37fa37adfd2345cd5e4b89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Manuel=20Tom=C3=A1s?= Date: Mon, 11 Jan 2021 09:59:53 -0300 Subject: Implement rem for P This one doesn't need shift. --- src/poly.rs | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/poly.rs b/src/poly.rs index 3f298cb..f6ee63c 100644 --- a/src/poly.rs +++ b/src/poly.rs @@ -4,7 +4,7 @@ use crate::number::Number; use iter::Iter; use std::cmp; use std::cmp::Ordering; -use std::ops::{Add, Sub, Mul}; +use std::ops::{Add, Sub, Mul, Rem}; use std::iter::{Sum, Zip, Take}; #[derive(PartialEq, Debug)] @@ -65,6 +65,26 @@ impl Mul for &P { } } +impl Rem for &P { + type Output = P; + + fn rem(self, other: Self) -> P { + let ad = self.degree(); + let bd = other.degree(); + let an = self.0[ad]; + let bn = other.0[bd]; + match ad.cmp(&bd) { + Ordering::Equal => self - &(other * &P(vec![an / bn])), + Ordering::Greater => { + let mut qv = vec![0.0; ad]; + qv[ad - bd] = an / bn; + self - &(other * &P(qv)) + }, + Ordering::Less => P(vec![0.0]) + } + } +} + //****************************REFACTORING************************************ pub type Poly = Vec; @@ -213,16 +233,16 @@ mod tests { #[test] fn rem_equal() { - let a = vec![6.0, 7.0, 1.0]; - let b = vec![-6.0, -5.0, 1.0]; - assert_eq!(rem(&a, &b), vec![12.0, 12.0, 0.0]); + let a = P(vec![6.0, 7.0, 1.0]); + let b = P(vec![-6.0, -5.0, 1.0]); + assert_eq!(&a % &b, P(vec![12.0, 12.0, 0.0])); } #[test] fn rem_greater() { - let a = vec![-6.0, -5.0, 1.0]; - let b = vec![12.0, 12.0, 0.0]; - assert_eq!(rem(&a, &b), vec![-6.0, -6.0, 0.0]); + let a = P(vec![-6.0, -5.0, 1.0]); + let b = P(vec![12.0, 12.0, 0.0]); + assert_eq!(&a % &b, P(vec![-6.0, -6.0, 0.0])); } #[test] -- cgit v1.2.3