65 lines
1.6 KiB
Rust
65 lines
1.6 KiB
Rust
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::<usize>();
|
|
match divisor_sum.cmp(&n) {
|
|
Ordering::Equal => Perfect,
|
|
Ordering::Less => Deficient,
|
|
Ordering::Greater => Abundant,
|
|
}
|
|
}
|
|
|
|
fn get_divisors(n: usize) -> Vec<usize> {
|
|
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
|
|
}
|