euler/src/bin/problem_21.rs
2024-09-16 12:42:55 +02:00

43 lines
1.5 KiB
Rust

use std::collections::{HashMap, HashSet};
use std::time::Instant;
fn main() {
let now = Instant::now();
let mut amicable_cache: HashMap<isize, isize> = HashMap::new();
let mut despicable_cache: HashMap<isize, isize> = HashMap::new();
let mut sum_amicable = 0;
for i in 2..10000 {
let divisors = get_divisors(i);
let sum_divisors = divisors.iter().sum();
if amicable_cache.get(&sum_divisors).is_some() {
continue;
}
if despicable_cache.get(&sum_divisors).is_some() {
continue;
}
let other_divisors = get_divisors(sum_divisors);
let other_sum_divisors = other_divisors.iter().sum();
if i == other_sum_divisors && i != sum_divisors {
amicable_cache.insert(other_sum_divisors, sum_divisors);
sum_amicable += sum_divisors + other_sum_divisors;
} else {
despicable_cache.insert(other_sum_divisors, sum_divisors);
}
}
println!("cache: {:?}", amicable_cache);
println!("sum: {sum_amicable}");
println!("Time={} µs", now.elapsed().as_micros());
}
fn get_divisors(n: isize) -> Vec<isize> {
let mut divisors = HashSet::from([1]);
let mut potential_divisor = 2;
while (potential_divisor * potential_divisor) <= n {
if n % potential_divisor == 0 {
divisors.insert(potential_divisor);
divisors.insert(n / potential_divisor);
}
potential_divisor = potential_divisor + 1;
}
divisors.iter().map(|&divisor| divisor).collect()
}