1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-08-04 23:17:46 +00:00

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.
This commit is contained in:
nicoo 2020-05-30 11:40:21 +02:00 committed by Alex Lyon
parent 4b4d11b61a
commit 2869248318

View file

@ -11,7 +11,7 @@ extern crate rand;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use std::collections::HashMap; use std::collections::BTreeMap;
use std::fmt; use std::fmt;
use std::io::{stdin, BufRead}; use std::io::{stdin, BufRead};
use std::ops; use std::ops;
@ -27,12 +27,12 @@ static SUMMARY: &str = "Print the prime factors of the given number(s).
static LONG_HELP: &str = ""; static LONG_HELP: &str = "";
struct Factors { struct Factors {
f: HashMap<u64, u8>, f: BTreeMap<u64, u8>,
} }
impl Factors { impl Factors {
fn new() -> Factors { fn new() -> Factors {
Factors { f: HashMap::new() } Factors { f: BTreeMap::new() }
} }
fn add(&mut self, prime: u64, exp: u8) { fn add(&mut self, prime: u64, exp: u8) {
@ -63,12 +63,8 @@ impl ops::MulAssign<Factors> for Factors {
impl fmt::Display for Factors { impl fmt::Display for Factors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: Use a representation with efficient in-order iteration for (p, exp) in self.f.iter() {
let mut primes: Vec<&u64> = self.f.keys().collect(); for _ in 0..*exp {
primes.sort();
for p in primes {
for _ in 0..self.f[&p] {
write!(f, " {}", p)? write!(f, " {}", p)?
} }
} }