python - 欧拉计划 #23 错误答案

标签 python algorithm python-3.x

我刚刚完成了项目欧拉问题编号 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 generator 几乎返回整数的所有非平凡除数,但不保证顺序。它通过 1 循环到 n 的平方根,并产生除数及其商。下一个函数is_abundant实际上检查 n 的除数之和是否小于 n 然后返回 False 否则返回 True。接下来是列表abundants它拥有从 1 到 28123 和 abundants_set 的所有丰富数字就像abundants但它是一个集合而不是列表。下一个函数是 is_abundant_**sum**这几乎检查了赋予函数的总和本身是否丰富,最后是不是 is_abundant_sum 的数字总和。打印出来。

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

如有任何帮助,我们将不胜感激。

最佳答案

除数 生成器重复计算f**2 的因子f。此错误会影响大量数字的计算列表。

关于python - 欧拉计划 #23 错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25475074/

相关文章:

Python,jsonpath : How do I parse with jsonpath correctly?

python - pandas 数据帧到 numpy 数组,没有烦人的 dtype ="blah blah"

algorithm - 在 iTunes 11 中为歌曲列表着色的算法是如何工作的?

algorithm - 以下表达式的时间复杂度是多少?

python-3.x - 如何在图像JtessBoxEditor上创建框?

python - 具有平方特征的 Pytorch 线性回归

c# - 用 IEnumerable 实现的快速排序的复杂度是多少?

Python Pandas 系列 if else 箱线图

python - 重新运行单元格时,Jupyter notebook 速度极慢

python - DataFrame 减去分组均值