// you’re reading...
1 Star2 Stars3 Stars4 Stars5 Stars (48 votes, average: 5.00 out of 5)
Loading...

Project Euler Solutions

Project Euler 23 Solution

Project Euler 23 Solution

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


Project Euler 23 Problem Description

Project Euler 23: 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 whose proper divisors are less than the number is called deficient and a number whose proper divisors exceed the number is called abundant.

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.

Analysis

Abundant numbers are numbers less than the sum of its factors, such as 12 < 1 + 2 + 3 + 4 + 6 or 12 < 16. The first 23 abundant numbers are:

12, 18, 20, 24, 30, 36, 40, 42, 48, 54, 56, 60, 66, 70, 72, 78, 80, 84, 88, 90, 96, 100, 102, …
Reference: The On-Line Encyclopedia of Integer Sequences (OEIS) A005101: Abundant numbers

The problem stated that all natural numbers greater than 28123 can be derived as a sum of two abundant numbers. But for numbers less than 28123 there are some exceptions. We are asked to find those exceptions and sum them for an answer.

Improving the search range

According to Wolfram Mathworld’s discussion on Abundant Numbers, “Every number greater than 20161 can be expressed as a sum of two abundant numbers.” So our upper bound lowered to 20161 from 28123.

Searching the range

As this problem is an investigative endeavor it can be solved easily by building a set of abundant numbers and searching the space below 20161 for those taget numbers which can’t be formed from the sum of two abundant numbers (addends). Keep in mind that the two addends can be the same abundant number, such as 12+12=24, which would exclude 24 from our target list of exceptions.

Following the algorithm

Let’s look at the process of building a set of abundant numbers and then checking which target numbers cannot be represented by adding two abundant numbers together (marked with an asterisk (‘*’)).

1	set([])         *	          21	set([20,18,12])                 *
2	set([])         *	          22	set([20,18,12])                 *
3	set([])         *	          23	set([20,18,12])                 *
4	set([])         *	          24	set([24,20,18,12])	
5	set([])         *	          25	set([24,20,18,12])              *
6	set([])         *	          26	set([24,20,18,12])              *
7	set([])         *	          27	set([24,20,18,12])              *
8	set([])         *	          28	set([24,20,18,12])              *
9	set([])         *	          29	set([24,20,18,12])              *
10	set([])         *	          30	set([24,20,18,12,30])	
11	set([])         *	          31	set([24,20,18,12,30])           *
12	set([12])       *	          32	set([24,20,18,12,30])	
13	set([12])       *	          33	set([24,20,18,12,30])           *
14	set([12])       *	          34	set([24,20,18,12,30])           *
15	set([12])       *	          35	set([24,20,18,12,30])           *
16	set([12])       *	          36	set([36,12,18,20,24,30])	
17	set([12])       *	          37	set([36,12,18,20,24,30])        *
18	set([18,12])    *	          38	set([36,12,18,20,24,30])	
19	set([18,12])    *	          39	set([36,12,18,20,24,30])        *
20	set([20,18,12]) *	          40	set([36,40,12,18,20,24,30])	

We consider each target number and, using the d() function, check to see if it is an abundant number. If it is then its added to our set of abundant numbers, abn.

The any function is used to make the necessary comparisons by taking the target number and subtracting each abundant number from the set and checking if the result is an abundant number. For example, the target number 30 is processed as:

  • 30-24=6, 6 is not in our set and therefore not an abundant number
  • 30-20=10, 10 is not in our set and therefore not an abundant number
  • 30-18=12 12 is in our set and therefore an abundant number. So 30 can be formed by the addition of two abundant numbers 12+18=30.

any is like a as series of logical or operators and processing stops and returns true as soon as one condition is met.

HackerRank Project Euler 23 has us query 100 numbers less than 100,000 and return “YES” or “NO” for every number that can or can not be represented by adding two abundant numbers. Any number greater than 20,161 will return “YES” and all others will be pre-calculated to a cache using this algorithm.

Project Euler 23
This program and method
solves all test cases for
Project Euler 23 on HackerRank

Project Euler 23 Solution

Runs < 0.530 seconds in Python 2.7.
def d(n):
    t = sqrt(n)
    s = -t if t.is_integer() else 1 
    for i in range(2, int(t)+1):
        if n % i == 0: s += i + n/i
    return s
 
L, s = 20161, 0
abn = set()

for n in range(1, L+1):
    if d(n) > n: abn.add(n)
    if not any( (n-a in abn) for a in abn ):
        s+= n
 
print "Project Euler 23 Solution =", s
download arrowUse this link to get the Project Euler 23 Solution Python 2.7 source.

Answer

Slowly swipe from either end beginning with the white vertical bar to get an idea of the starting or ending digits. For less drama, just double click the answer area. The distance between the two bars will give you an idea of the magnitude. Touch devices can tap and hold the center of the box between the two bars and choose define to reveal the answer.
|4179871|

Afterthoughts

Project Euler 23 Solution last updated

Discussion

10 Responses to “Project Euler 23 Solution”

  1. Hello, maybe 3 years too late, but I hope you can help me find the flaw in my code. I have checked that my versión of the function for summing up proper divisors works alright; so the problems must be the other one, yet I can’t figure out where.

    def divSum(n):
        div = 1
        divs = []
        while True:
            if n  n:
                abundants.add(n)
            for number in abundants:
                if (n - number) in abundants:
                    isSum = True
            if not isSum:
                totalSum += n
        return totalSum
    

    Posted by Miguel | November 27, 2016, 1:08 PM
  2. I get an error when I try to import from Euler, so I constructed the d list from scratch. This is my code and it gives an answer of 4123438 which is apparently wrong. Obviously I am a beginner in Python. Where have I gone wrong? Thank you.

    sm=0
    d = []

    for x in range(1,20163):
    sm=0
    for y in range(1,x-1):
    if x%y == 0:
    sm = sm + y
    next

    d.append(sm)

    # print x, sm
    next

    #for x in range(1,len(d)):
    # print x, d[x]

    L, s = 20162, 0
    abn = set()

    for n in range(1, L):
    if d[n] > n:
    abn.add(n)
    if not any( (n-a in abn) for a in abn ):
    s += n

    print “Answer to PE23 =”, s

    Posted by Thomas Babonis | March 13, 2014, 5:41 AM
    • Here’s a solution with the ‘d’ function explicitly defined.

      #Calculate the sum of proper divisors for n
      def d(n):
          s = 1
          t = n ** 0.5
          for i in range(2, int(t)+1):
              if n % i == 0: s += i + n/i
          if t == int(t): s -= t    #correct s if t is a perfect square
          return s
       
      L, s = 20162, 0
      abn = set()
       
      for n in range(1, L):
          if d(n) > n:
              abn.add(n)
          if not any( (n-a in abn) for a in abn ):
              s += n
       
      print "Answer to PE23 =", s
      

      You can find my Python Euler library here:
      Project Euler Library

      Posted by Mike | March 13, 2014, 5:03 PM
  3. Can you explain this line in your second function?

    if not any( (n-a in abn) for a in abn ):
    s += n

    and also this line in your first function:
    if t == int(t): s -= t

    Posted by John | February 2, 2013, 2:04 PM
  4. Hi, I’m new on python and I just start the project-euler. I think I learned a lot from your code. It’s really amazing!

    Posted by kilimanjaroup | August 17, 2012, 3:55 AM

Post a comment