speed up proper divisor algorithm (95)

This commit is contained in:
Dr. Matthias Ratajczak
2023-06-28 15:15:27 +02:00
parent 5cb8d0cfe7
commit 3d588cc232
+28 -4
View File
@@ -23,6 +23,10 @@ fn main() {
println!("{smallest}");
}
fn build_proper_divisors(max: usize) -> Vec<Vec<usize>> {
todo!()
}
fn try_build_chain_from_number(
max: usize,
mut current: usize,
@@ -34,7 +38,7 @@ fn try_build_chain_from_number(
loop {
maybe_chain.push(current);
let next: usize = get_proper_divisors(current).sum();
let next: usize = get_proper_divisors(current).into_iter().sum();
if next > max || next == 0 {
break;
@@ -55,9 +59,29 @@ fn try_build_chain_from_number(
}
}
fn get_proper_divisors(x: usize) -> impl Iterator<Item = usize> {
fn get_proper_divisors(x: usize) -> Vec<usize> {
let mut result = vec![1];
let limit = x / 2 + 1;
(1..limit).filter(move |i| x % *i == 0)
for i in 2..limit {
if result.contains(&i) {
break;
}
if x % i == 0 {
let div_1 = i;
let div_2 = x / i;
result.push(div_1);
if div_2 != div_1 {
result.push(div_2);
}
}
}
result.sort_unstable();
result
}
#[cfg(test)]
@@ -72,7 +96,7 @@ mod tests {
fn proper_divisor(#[case] input: usize, #[case] expected: Vec<usize>) {
use crate::get_proper_divisors;
assert_eq!(get_proper_divisors(input).collect::<Vec<_>>(), expected);
assert_eq!(get_proper_divisors(input), expected);
}
#[rstest]