Rust Implementation of Problem 23

View source code here on GitHub!

Problem Solution

pub fn problems::p0023::p0023() -> utils::Answer
 1/*
 2Project Euler Problem 23
 3
 4I had to approach this by modifying the factors function from p0003, but it
 5seemed to work fairly well.
 6
 7Problem:
 8
 9A perfect number is a number for which the sum of its proper divisors is
10exactly equal to the number. For example, the sum of the proper divisors of 28
11would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
12
13A number n is called deficient if the sum of its proper divisors is less than n
14and it is called abundant if this sum exceeds n.
15
16As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest
17number that can be written as the sum of two abundant numbers is 24. By
18mathematical analysis, it can be shown that all integers greater than 28123 can
19be written as the sum of two abundant numbers. However, this upper limit cannot
20be reduced any further by analysis even though it is known that the greatest
21number that cannot be expressed as the sum of two abundant numbers is less than
22this limit.
23
24Find the sum of all the positive integers which cannot be written as the sum of
25two abundant numbers.
26*/
27use std::collections::HashSet;
28
29use crate::include::factors::proper_divisors;
30use crate::include::utils::Answer;
31
32pub fn p0023() -> Answer {
33    let mut abundant_sums: HashSet<u64> = HashSet::new();
34    abundant_sums.insert(24);
35    let mut abundants: Vec<u64> = vec![];
36    
37    for x in 12..28112 {
38        if proper_divisors::<u64>(x).sum::<u64>() > x {
39            abundants.push(x);
40        }
41    }
42    for x in abundants.clone().into_iter() {
43        for y in &abundants {
44            abundant_sums.insert(x + y);
45        }
46    }
47    let mut sum = 0;
48    for x in 1..28124 {
49        if !abundant_sums.contains(&x) {
50            sum += x;
51        }
52    }
53    return Answer::Int(sum.into());
54}

Tags: large-numbers, digit-sum, factorial