# Euler Problem 23¶

Back to overview.

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.

We reuse the sum of proper divisors function and use it to tell whether a number is abundant or not.

In [20]:

    def sum_of_proper_divisors(n):
        from math import sqrt
        if n == 1:
            return 0
        s = 1
        for i in range(2, int(sqrt(n)) + 1):
            if n % i == 0:
                s += i
                x = (n // i)
                if x != i:
                    s += x
        return s

    def is_abundant(n):
        return sum_of_proper_divisors(n) > n

    assert(is_abundant(7) == False)
    assert(is_abundant(12) == True)

    abundant_numbers_smaller_30000 = [n for n in range(1, 30001) if is_abundant(n)]
    abundant_numbers_smaller_30000_set = set(abundant_numbers_smaller_30000)

Now that we have all abundant numbers in sorted order we can write a function which tests whether a number can be written as a sum of two abundant numbers.

In [21]:

    def is_sum_of_two_abundants(n):
        for a in abundant_numbers_smaller_30000:
            if a > (n // 2):
                return False
            r = n - a
            if r in abundant_numbers_smaller_30000_set:
                return True
        return False

    assert(is_sum_of_two_abundants(24) == True)
    assert(is_sum_of_two_abundants(23) == False)
    assert(is_sum_of_two_abundants(28123) == True)

Now we try to brute force.

In [34]:

    s = sum([i for i in range(1, 30000) if not is_sum_of_two_abundants(i)])
    print(s)
    assert(s == 4179871)

    4179871