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.
I sum the proper divisors of each positive integer below \(21823\) in the same way as in problem 21. After that, I identify all such numbers which are abundant and place them into a list \(A\). I then iterate over all pairs of integers in \(A\) and see which numbers below \(21823\) are the sum of any such pair, then add up all the ones that aren't.
def p23():
cap = 21823
sigma = [1 for i in range(cap)]
for p in primerange(cap):
px = p
while px < cap:
for m in range(px, cap, px):
sigma[m] = sigma[m] * (px * p - 1) // (px - 1)
px *= p
A = list(filter(lambda k: sigma[k] > 2 * k, range(1, cap)))
B = [True for _ in range(cap)]
for i in range(len(A)):
for j in range(i, len(A)):
if A[i] + A[j] >= cap:
break # A is sorted, so this saves time
B[A[i] + A[j]] = False
return sum(filter(lambda k: B[k], range(cap)))