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

factor::rho: Refactor to avoid unnecessary allocations

This commit is contained in:
nicoo 2020-06-19 14:03:11 +02:00
parent 71e1c52920
commit dacee413db
2 changed files with 10 additions and 5 deletions

View file

@ -36,6 +36,13 @@ impl Factors {
Factors { f: BTreeMap::new() } Factors { f: BTreeMap::new() }
} }
fn prime(p: u64) -> Factors {
debug_assert!(miller_rabin::is_prime(p));
let mut f = Factors::one();
f.push(p);
f
}
fn add(&mut self, prime: u64, exp: u8) { fn add(&mut self, prime: u64, exp: u8) {
debug_assert!(exp > 0); debug_assert!(exp > 0);
let n = *self.f.get(&prime).unwrap_or(&0); let n = *self.f.get(&prime).unwrap_or(&0);

View file

@ -55,17 +55,15 @@ fn _factor<A: Arithmetic>(num: u64) -> Factors {
_factor::<A>(n) _factor::<A>(n)
}; };
let mut factors = Factors::one();
if num == 1 { if num == 1 {
return factors; return Factors::one();
} }
let n = A::new(num); let n = A::new(num);
let divisor; let divisor;
match miller_rabin::test::<A>(n) { match miller_rabin::test::<A>(n) {
Prime => { Prime => {
factors.push(num); return Factors::prime(num);
return factors;
} }
Composite(d) => { Composite(d) => {
@ -77,7 +75,7 @@ fn _factor<A: Arithmetic>(num: u64) -> Factors {
} }
}; };
factors *= _factor(divisor); let mut factors = _factor(divisor);
factors *= _factor(num / divisor); factors *= _factor(num / divisor);
factors factors
} }