More simplification
This commit is contained in:
parent
664ea1528a
commit
c4e1e274f9
1 changed files with 9 additions and 18 deletions
|
@ -1,28 +1,22 @@
|
|||
pub fn factors(n: u64) -> Vec<u64> {
|
||||
let n = n
|
||||
.try_into()
|
||||
.expect("usize is not large enough to factor a u64");
|
||||
let bound = isqrt(n);
|
||||
|
||||
let mut factors = {
|
||||
// Worst case number of factors is a power of 2, number of
|
||||
// factors will be the number of bits needed to represent
|
||||
// the number.
|
||||
let capacity = ilog2(n);
|
||||
let capacity = ilog2(n)
|
||||
.try_into()
|
||||
.expect("number of bits should not exceed usize::MAX");
|
||||
Vec::with_capacity(capacity)
|
||||
};
|
||||
|
||||
let mut reduced = n;
|
||||
'outer: for i in 2..=bound {
|
||||
while reduced % i == 0 {
|
||||
{
|
||||
let i = i
|
||||
.try_into()
|
||||
.expect("round-trip conversion from u64 to usize loses precision");
|
||||
// Ensure we allocated enough capacity for all factors.
|
||||
assert!(factors.len() < factors.capacity());
|
||||
factors.push(i);
|
||||
}
|
||||
// Ensure we allocated enough capacity for all factors.
|
||||
assert!(factors.len() < factors.capacity());
|
||||
factors.push(i);
|
||||
reduced /= i;
|
||||
if reduced == 0 {
|
||||
break 'outer;
|
||||
|
@ -31,9 +25,6 @@ pub fn factors(n: u64) -> Vec<u64> {
|
|||
}
|
||||
|
||||
if reduced > 1 {
|
||||
let reduced = reduced
|
||||
.try_into()
|
||||
.expect("round-trip conversion from u64 to usize loses precision");
|
||||
// Ensure we allocated enough capacity for all factors.
|
||||
assert!(factors.len() < factors.capacity());
|
||||
factors.push(reduced);
|
||||
|
@ -42,10 +33,10 @@ pub fn factors(n: u64) -> Vec<u64> {
|
|||
factors
|
||||
}
|
||||
|
||||
fn ilog2(n: usize) -> usize {
|
||||
(n.checked_ilog2().unwrap_or(0)) as _
|
||||
fn ilog2(n: u64) -> u32 {
|
||||
n.checked_ilog2().unwrap_or(0)
|
||||
}
|
||||
|
||||
fn isqrt(n: usize) -> usize {
|
||||
fn isqrt(n: u64) -> u64 {
|
||||
(n as f64).sqrt() as _
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue