Euler项目23错误答案

2024-07-03 07:03:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚完成了ProjectEuler问题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 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.

这是我的解决方案:

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)

我的回答是:3906313

我的代码说明: divisors生成器几乎返回整数的所有非平凡除数,但对顺序没有保证。它循环遍历n的1到平方根,得到除数及其商。下一个函数is_abundant实际上检查n的除数之和是否小于n,然后返回False,否则返回True。接下来是列表abundants,它包含从1到28123的所有富余数,abundants_set就像abundants,但它是一个集合而不是列表。下一个函数是is_abundant_**sum**,它几乎检查给函数的和本身是否充足,最后打印出不是is_abundant_sum的数的和。在

我哪里做错了?我的代码有什么问题?在

任何帮助都将不胜感激。在


Tags: oftheinnumberforifthatis