feat(21): complete amicable numbers

This commit is contained in:
newt 2024-10-09 18:10:13 +01:00
parent 68e02a020b
commit 6ab9e999b5
3 changed files with 48 additions and 1 deletions

View file

@ -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

44
src/bin/21.rs Normal file
View file

@ -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<usize> {
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<usize> {
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::<usize>();
println!("The sum of the first 9,999 amicable numbers is {sum}!");
}

View file

@ -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!(