From c4e1e274f987d6cbe7c548ad846983284e4a6999 Mon Sep 17 00:00:00 2001 From: Avery Winters Date: Wed, 6 Nov 2024 14:50:01 -0600 Subject: [PATCH] More simplification --- rust/prime-factors/src/lib.rs | 27 +++++++++------------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/rust/prime-factors/src/lib.rs b/rust/prime-factors/src/lib.rs index 1aa4c8f..5d7e7ea 100644 --- a/rust/prime-factors/src/lib.rs +++ b/rust/prime-factors/src/lib.rs @@ -1,28 +1,22 @@ pub fn factors(n: u64) -> Vec { - 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 { } 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 { 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 _ }