Project Euler第50题内容如下:
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?
在我的方法中,我使用埃拉托色尼筛法预先生成一个素数列表,然后 在函数本身中,我不断添加素数列表的后续元素 每次我这样做时,我都会检查总和本身是否为素数,如果是,我会跟踪它作为最大的一个并返回它。好吧,我想那应该有用吗?显然答案不正确,但有趣的是,当我更改筛子以生成低于 100000 的素数时,它不会给出索引错误,但会给出另一个结果。
from algorithms import gen_primes
primes = [i for i in gen_primes(1000000)]
def main(n):
idx, total, maximum = 0, 0, 0
while total < n:
total += primes[idx]
idx += 1
if total in primes:
maximum = total
return maximum
print(main(1000000))
请您参考如下方法:
您的程序没有解决一般问题:您总是从最低的 2 开始您的连续素数列表。因此,您返回的是从 2* 开始的最长连续列表,而不是任何 连续素数列表。
简而言之,你需要另一个循环......
start_idx = 0
while start_idx < len(primes) and best_len*primes[start_idx] < n:
# find longest list starting at primes[start_idx]
start_idx += 1
如果有任何帮助,成功的序列从 1500 到 2000 之间开始。
