Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Euler #23 Incorrect Answer

I have just completed my solution for project euler problem number 23 which states:

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.

This is my solution:

from math import sqrt
def divisors(n):
    for i in range(2, 1 + int(sqrt(n))):
        if n % i == 0:
            yield i
            yield n / i

def is_abundant(n):
    return 1 + sum(divisors(n)) > n

abundants = [x for x in range(1, 28123 + 1) if is_abundant(x)]
abundants_set = set(abundants)

def is_abundant_sum(n):
   for i in abundants:
       if i > n:  # assume "abundants" is ordered
         return False
       if (n - i) in abundants_set:
           return True
   return False

sum_of_non_abundants = sum(x for x in range(1, 28123 + 1) if not is_abundant_sum(x))
print(sum_of_non_abundants)

My answer is: 3906313

Explanation of my code: The divisors generator pretty much returns all nontrivial divisors of an integer, but makes no guarantees on the order. It loops through 1 to square root of n and yields the divisor and its quotient. The next function is_abundant actually checks if sum of divisors of n is less than n then return False else return True. Next is the list abundants which holds all the abundant numbers from 1 to 28123 and abundants_set is just like abundants but instead it's a set not a list. The next function is is_abundant_**sum** which pretty much checks if the sum given to the functions is itself abundant or not and in the end the sum of numbers which are not is_abundant_sum is printed.

Where did I do wrong? What's the problem in my code?

Any help would be appreciated.

like image 491
Mohammad Areeb Siddiqui Avatar asked Aug 30 '26 11:08

Mohammad Areeb Siddiqui


1 Answers

The divisors generator double counts the factor f of f**2. This bug affects the computed list of abundant numbers.

like image 164
David Eisenstat Avatar answered Sep 01 '26 02:09

David Eisenstat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!