1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-29 12:07:46 +00:00

factor::Decomposition: Optimise as a factor is never added twice

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.
This commit is contained in:
nicoo 2020-07-31 15:03:27 +02:00 committed by Roy Ivy III
parent ce218e01b6
commit b7b0c76b8e

View file

@ -25,12 +25,10 @@ impl Decomposition {
fn add(&mut self, factor: u64, exp: Exponent) { fn add(&mut self, factor: u64, exp: Exponent) {
debug_assert!(exp > 0); 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) { self.0.push((factor, exp))
*e += exp;
} else {
self.0.push((factor, exp))
}
} }
fn is_one(&self) -> bool { fn is_one(&self) -> bool {