diff --git a/src/bin/problem_12.rs b/src/bin/problem_12.rs index 2014ada..24a6c5b 100644 --- a/src/bin/problem_12.rs +++ b/src/bin/problem_12.rs @@ -25,5 +25,9 @@ fn get_divisors(n: usize) -> Vec { } potential_divisor = potential_divisor + 1; } + // This almost made me go mad + if potential_divisor * potential_divisor == n { + divisors.push(potential_divisor) + } divisors } diff --git a/src/bin/problem_23.rs b/src/bin/problem_23.rs new file mode 100644 index 0000000..e52adac --- /dev/null +++ b/src/bin/problem_23.rs @@ -0,0 +1,64 @@ +use std::cmp::Ordering; +use crate::NumberType::{Abundant, Deficient, Perfect}; + +// 4179871 + +fn main() { + let mut abundants = vec![]; + let mut sum = 0; + let upper_bound = 28123; + for num in 1..=upper_bound { + let num_type = get_number_type(num); + if num_type == Abundant { + abundants.push(num); + } + let mut contained = false; + for abundant in &abundants { + match abundants.binary_search(&(num-abundant)) { + Ok(_) => { + contained = true; + break; + } + Err(_) => {} + } + } + if !contained { + sum += num; + } + } + //println!("{:?}", abundants); + println!("{sum}"); +} + +#[derive(Eq, PartialEq)] +enum NumberType { + Perfect, + Deficient, + Abundant, +} + +fn get_number_type(n: usize) -> NumberType { + let divisor_sum = get_divisors(n).iter().sum::(); + match divisor_sum.cmp(&n) { + Ordering::Equal => Perfect, + Ordering::Less => Deficient, + Ordering::Greater => Abundant, + } +} + +fn get_divisors(n: usize) -> Vec { + let mut divisors = vec![1]; + let mut potential_divisor = 2; + while (potential_divisor * potential_divisor) < n { + if n % potential_divisor == 0 { + divisors.push(potential_divisor); + divisors.push(n / potential_divisor); + } + potential_divisor = potential_divisor + 1; + } + // This almost made me go mad, should have used the one from 21 + if potential_divisor * potential_divisor == n { + divisors.push(potential_divisor) + } + divisors +}