From 2869248318a44db411c236058c8e332451ae60e9 Mon Sep 17 00:00:00 2001 From: nicoo Date: Sat, 30 May 2020 11:40:21 +0200 Subject: [PATCH] factor::Factors: Use a tree-based map internally This eliminate the need for sorting the prime factors for display. 25% performance improvement after the changes from factor/montgomery. --- src/uu/factor/src/factor.rs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/uu/factor/src/factor.rs b/src/uu/factor/src/factor.rs index 457bed6bb..4dd0fa5a7 100644 --- a/src/uu/factor/src/factor.rs +++ b/src/uu/factor/src/factor.rs @@ -11,7 +11,7 @@ extern crate rand; #[macro_use] extern crate uucore; -use std::collections::HashMap; +use std::collections::BTreeMap; use std::fmt; use std::io::{stdin, BufRead}; use std::ops; @@ -27,12 +27,12 @@ static SUMMARY: &str = "Print the prime factors of the given number(s). static LONG_HELP: &str = ""; struct Factors { - f: HashMap, + f: BTreeMap, } impl Factors { fn new() -> Factors { - Factors { f: HashMap::new() } + Factors { f: BTreeMap::new() } } fn add(&mut self, prime: u64, exp: u8) { @@ -63,12 +63,8 @@ impl ops::MulAssign for Factors { impl fmt::Display for Factors { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - // TODO: Use a representation with efficient in-order iteration - let mut primes: Vec<&u64> = self.f.keys().collect(); - primes.sort(); - - for p in primes { - for _ in 0..self.f[&p] { + for (p, exp) in self.f.iter() { + for _ in 0..*exp { write!(f, " {}", p)? } }