From b7b0c76b8ea60297b43777d17d7322d1d45a9e91 Mon Sep 17 00:00:00 2001 From: nicoo Date: Fri, 31 Jul 2020 15:03:27 +0200 Subject: [PATCH] factor::Decomposition: Optimise as a factor is never added twice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The invariant is checked by a debug_assert!, and follows from the previous commit, as `dec` and `factors` only ever contains coprime numbers: - true at the start: factor = ∅ and dec = { n¹ } ; - on every loop iteration, we pull out an element `f` from `dec` and either: - discover it is prime, and add it to `factors` ; - split it into a number of coprime factors, that get reinserted into `dec`; the invariant is maintained, as all divisors of `f` are coprime with all numbers in `dec` and `factors` (as `f` itself is coprime with them. As we only add elements to `Decomposition` objects that are coprime with the existing ones, they are distinct. --- src/uu/factor/src/factor.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/uu/factor/src/factor.rs b/src/uu/factor/src/factor.rs index 3f0f73c9b..7dc4b90d9 100644 --- a/src/uu/factor/src/factor.rs +++ b/src/uu/factor/src/factor.rs @@ -25,12 +25,10 @@ impl Decomposition { fn add(&mut self, factor: u64, exp: Exponent) { debug_assert!(exp > 0); + // Assert the factor doesn't already exist in the Decomposition object + debug_assert_eq!(self.0.iter_mut().find(|(f, _)| *f == factor), None); - if let Some((_, e)) = self.0.iter_mut().find(|(f, _)| *f == factor) { - *e += exp; - } else { - self.0.push((factor, exp)) - } + self.0.push((factor, exp)) } fn is_one(&self) -> bool {