diff --git a/readme.md b/readme.md index 487b875..07e6601 100644 --- a/readme.md +++ b/readme.md @@ -39,7 +39,7 @@ Here is a [link to my profile](https://projecteuler.net/progress=newtykins). - [x] 18 - [Maximum path sum I](src/bin/18.rs) - [x] 19 - Counting Sundays - [x] 20 - Factorial digit sum -- [ ] 21 - Amicable numbers +- [x] 21 - Amicable numbers - [x] 22 - [Names scores](src/bin/22.rs) - [ ] 23 - Non-abundant sums - [ ] 24 - Lexicographic permutations diff --git a/src/bin/21.rs b/src/bin/21.rs new file mode 100644 index 0000000..4fbb5e2 --- /dev/null +++ b/src/bin/21.rs @@ -0,0 +1,44 @@ +/* +Problem 21 - Amicable Numbers + +Let $d(n)$ be defined as the sum of proper divisors of $n$ (numbers less than $n$ which divide evenly into $n$). +If $d(a) = b$ and $d(b) = a$, where $a \ne b$, then $a$ and $b$ are an amicable pair and each of $a$ and $b$ are called amicable numbers. +For example, the proper divisors of $220$ are $1, 2, 4, 5, 10, 11, 20, 22, 44, 55$ and $110$; therefore $d(220) = 284$. The proper divisors of $284$ are $1, 2, 4, 71$ and $142$; so $d(284) = 220$. +Evaluate the sum of all the amicable numbers under $10000$. +*/ + +fn proper_divisors(number: usize) -> Vec { + let mut divisors = vec![1]; + + for divisor in 2..=(number / 2) { + if number % divisor == 0 { + divisors.push(divisor); + } + } + + divisors +} + +fn d(number: usize) -> usize { + proper_divisors(number).iter().sum() +} + +fn amicable_numbers(upper_bound: usize) -> Vec { + let mut amicable_numbers = Vec::new(); + + for a in 2..upper_bound { + let b = d(a); + + if a != b && d(b) == a { + amicable_numbers.push(a); + } + } + + amicable_numbers +} + +pub fn main() { + let sum = amicable_numbers(10_000).iter().sum::(); + + println!("The sum of the first 9,999 amicable numbers is {sum}!"); +} diff --git a/src/commands/run.rs b/src/commands/run.rs index 01876a6..5d29bbd 100644 --- a/src/commands/run.rs +++ b/src/commands/run.rs @@ -44,6 +44,8 @@ mod three; mod twelve; #[path = "../bin/20.rs"] mod twenty; +#[path = "../bin/21.rs"] +mod twenty_one; #[path = "../bin/27.rs"] mod twenty_seven; #[path = "../bin/22.rs"] @@ -90,6 +92,7 @@ pub async fn execute( 67 => sixty_seven::main(), 19 => nineteen::main(), 20 => twenty::main(), + 21 => twenty_one::main(), _ => { exists = false; println!(