繁体   English   中英

Project Euler #23 优化

[英]Project Euler #23 Optimization

不丰富的款项

问题 23

如果一个数 n 的真除数之和超过 n,则称其为富余数。 找出所有不能写为两个丰富数之和的正整数之和。

我已经尝试了几件事,并以我有限的编码知识尽可能地优化了我的代码。 前几天开始学习如何编码,发现了这个页面,(project euler),我有点偏离了学习,刚开始编码来尝试解决问题。 到目前为止,我已经设法在不花很长时间的情况下解决了大多数最简单的问题,但相比之下,这个问题花费的时间太长了。 对不起,如果我的代码无法理解。

sum_abundant = []
for i in abundant:
    for n in abundant:
        c = i + n
        if n > i:
            break
        if c < 28123:
            if c not in sum_abundant:  # if the number has already been removed, it won't remove it again.
                sum_abundant.append(c)

(“丰富”是一个包含所有丰富数字的列表。)它不是整个代码,只是我认为它花费大部分时间的部分。

您可以采取的一种方法是将问题分解为中间步骤:

  • 确定直到 28123 的所有数字的适当除数
  • 使用除数列表选择“丰富”的数字
  • 找到所有的丰富数字对并标记它们的总和
  • 选择没有被前面步骤标记的数字(那些将是不能表示为两个丰度之和的数字)
  • 计算这个结果的总和

这是一个例子:

# Create a list of proper divisora for all numbers up to 28123...

properDivs     = [ [] for _ in range(28124) ] 
for n in range(1,28124):
    for i in range(2*n,28124,n):
        properDivs[i].append(n)

# Select the numbers that are abundant (sum of divisors > number itself)...

abundants = [n for n,divs in enumerate(properDivs) if sum(divs)>n]

# Find all pairs of abundant numbers and flag their sums

from itertools import combinations_with_replacement
sumOf2Abundants = [False for _ in range(28124)]
for a,b in combinations_with_replacement(abundants,2):
    if a+b<len(sumOf2Abundants):
        sumOf2Abundants[a+b] = True

# Select numbers that were not flagged...

result = [n for n,isSumOf2 in enumerate(sumOf2Abundants) if not isSumOf2]

# compute and print the sum of the above result

print(sum(result))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM