Rust Implementation of Problem 21

View source code here on GitHub!

Problem Solution

pub fn problems::p0021::p0021() -> utils::Answer
 1/*
 2Project Euler Problem 21
 3
 4I had to approach this by modifying the factors function from p0003, but it
 5seemed to work fairly well.
 6
 7Revision 1:
 8
 9Rewrote the proper_divisors function to be significantly faster by leveraging
10the prime_factors object.
11
12Problem:
13
14Let d(n) be defined as the sum of proper divisors of n (numbers less than n
15which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and
16b are an amicable pair and each of a and b are called amicable numbers.
17
18For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55
19and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and
20142; so d(284) = 220.
21
22Evaluate the sum of all the amicable numbers under 10000.
23*/
24use crate::include::factors::proper_divisors;
25use crate::include::utils::Answer;
26
27fn d(n: u16) -> u16 {
28    return proper_divisors(n).sum::<u16>();
29}
30
31pub fn p0021() -> Answer {
32    let mut answer = 0;
33    let mut collection: Vec<u16> = (0..10000).collect();
34    for i in 0..collection.len() {
35        let a = collection[i];
36        let b = d(a);
37        if a != b && d(b) == a {
38            answer += a + b;
39            collection.retain(|&x| x != b);
40        }
41    }
42    return Answer::Int(answer.into());
43}

Tags: divisor-sum, prime-number, factorization, divisibility, rust-iterator