Question

I am unable to get the right output for the following:

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.

def check(n):
  s=0
  for i in xrange(1,n/2+1):
    if n%i==0:
      s+=i
  return s>n
l=100
sieve=[True]*l
for i in xrange(12):
  sieve[i]=False

abundant=[]
for i in xrange(12,l):
  if check(i):
    abundant.append(i)

for i in xrange(len(abundant)-1):
  for j in xrange(i+1,len(abundant)):
    if abundant[i]+abundant[j]<l:
      if sieve[abundant[i]+abundant[j]]==True:
        sieve[abundant[i]+abundant[j]]=False
        print abundant[i]+abundant[j]

print sum([i for i in xrange(len(sieve)) if sieve[i]])
Was it helpful?

Solution

The correct solution is 4179871 according to this.

Here is how you want to fix your code:

def check(n):
  s=0
  for i in xrange(1,n/2+1):
    if n%i==0:
      s+=i
  return s>n

l=28123 # upper bound of a number that is not the sum of 2 abundant numbers
sieve=[False]*l # sieve[i] == True means i IS the sum of 2 abundant numbers

abundant=[]
for i in xrange(12,l):
  if check(i):
    abundant.append(i)

for i in xrange(len(abundant)): # ranges here are such that you don't forget something like 2*abundant[-1]
  for j in xrange(i,len(abundant)):
    if abundant[i]+abundant[j]<l:
      sieve[abundant[i]+abundant[j]]=True 

print sum([i for i in xrange(len(sieve)) if not(sieve[i])])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top