60 Days of Euler in F# - Problem 23

The Problem

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

The Solution

We'll start out by stealing the findDivisors and sumDivisors functions from Problem 21

let intsqrt i = int(sqrt(float i))

let findDivisors n =
    let upperBound = intsqrt n
 
    [1..upperBound]
    |> Seq.filter (fun d -> n % d = 0)
    |> Seq.collect (fun d -> [d; n/d])
    |> Seq.filter (fun d -> d <> n)
    |> Seq.distinct

let sumDivisors n = findDivisors n |> Seq.sum

Next, we'll figure out if a number is "abundant" and use it to find all the abundant numbers < 28123. We only care about abundant numbers in this range because the (somewhat wordy) problem definition tells us that all the numbers we're looking for are less than 28123. Thus, even though there may be "abundant numbers" greater than this, we don't care about them.

let isAbundant n = sumDivisors n > n

let abundants =
    seq { 1..28122 }
    |> Seq.filter isAbundant
    |> Array.ofSeq

Next, we need a fast way to determine if a given number is the sum of two abundant numbers. We'll create a map by cross joining the array of abundants with itself, computing the sum of each pair, and building a map.

let crossSums = 
    seq {
        for a in abundants do
            for b in abundants do
                let sum = a+b
                yield sum,sum
    }

let sumMap = crossSums |> Map.ofSeq

With that map in hand, we can find the answer.

seq { 1..28123 }
|> Seq.filter (fun i -> not(sumMap.ContainsKey i))
|> Seq.sum

We simply filter out all numbers in the range that don't match one of our previously computed sums. Then we sum the remaining ones.

Other Posts in This Series