Project Euler Solution 23: Non-abundant sums
In today's installment of the Project Euler series we have Problem 23: Non-abundant sums which is again about divisors.
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.
For this I use plain brute force. And because it was too slow in pure Python, I used the NumPy library which is accelerated with native code. First I created all the abundant numbers up until the threshold of 28,123. Then I form the sum of all possible pairs of abundant numbers. This is done by making a NumPy array with all these abundant numbers. Then I broadcast it into a square matrix by just copying elements. From there on I can create a transposed copy and add them up. This way I will have a two dimensional array with the sums of abundant numbers.
From there on I just take the unique values smaller than that threshold. I create a boolean vector of that length and just set all sums of abundant numbers to false. All the other numbers are the ones that we are interested in. I get those and take the sum of them.
def solution() -> int: abundant_numbers = [ number for number in range(1, 28125) if sum(get_all_divisors(number)) > number ] an_vector = np.array(abundant_numbers) an_matrix = np.broadcast_to( an_vector, (len(abundant_numbers), len(abundant_numbers)) ) sums = an_matrix + an_matrix.T is_viable = np.ones((28125,)) not_viable = np.array([s for s in set(sums.flatten()) if s < 28125]) is_viable[not_viable] = 0 return sum(np.arange(len(is_viable))[is_viable == 1].tolist())
This takes quite long, 5413.900 ms. Compared to the other problems it is pretty slow. However, it is still within the one-minute-rule. Perhaps there is a better way to do it.