Skip to content

Commit

Permalink
Refactor fast factorial algorithm (#761)
Browse files Browse the repository at this point in the history
* Refactor fast factorial: Rename `p_indeces` -> `p_indices`

* Refactor fast factorial: rework `p_indices`

Collect indices into the map using `Iterator::collect` instead of
iterating each prime and inserting it

* Refactor fast factorial: better vector of ones

Avoid unnecessary resizing and just use `vec![]` macro directly

---------

Co-authored-by: Piotr Idzik <[email protected]>
  • Loading branch information
bgdnrvsky and vil02 committed Jul 15, 2024
1 parent 3481e51 commit 46ad2da
Showing 1 changed file with 7 additions and 9 deletions.
16 changes: 7 additions & 9 deletions src/big_integer/fast_factorial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,19 @@ pub fn fast_factorial(n: usize) -> BigUint {
// get list of primes that will be factors of n!
let primes = sieve_of_eratosthenes(n);

let mut p_indeces = BTreeMap::new();

// Map the primes with their index
primes.into_iter().for_each(|p| {
p_indeces.insert(p, index(p, n));
});
let p_indices = primes
.into_iter()
.map(|p| (p, index(p, n)))
.collect::<BTreeMap<_, _>>();

let max_bits = p_indeces.get(&2).unwrap().next_power_of_two().ilog2() + 1;
let max_bits = p_indices.get(&2).unwrap().next_power_of_two().ilog2() + 1;

// Create a Vec of 1's
let mut a = Vec::with_capacity(max_bits as usize);
a.resize(max_bits as usize, BigUint::one());
let mut a = vec![BigUint::one(); max_bits as usize];

// For every prime p, multiply a[i] by p if the ith bit of p's index is 1
for (p, i) in p_indeces {
for (p, i) in p_indices {
let mut bit = 1usize;
while bit.ilog2() < max_bits {
if (bit & i) > 0 {
Expand Down

0 comments on commit 46ad2da

Please sign in to comment.