我正在研究Project Euler Problem 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?
为了确定素数P中的项(如果它可以写成素数的总和),我使用所有素数的滑动窗口(按递增顺序)直到(但不包括)P,并计算所有的总和这些窗口,如果总和等于考虑的素数,我算一下窗口的长度……
这适用于1000以下的所有素数,但是对于高达10 ** 6的素数来说它非常慢,所以我希望备忘录会有所帮助;在计算滑动窗口的总和时,做了很多双重工作……(对吧?)
所以我在网上找到了标准的memoizaton实现,并将其粘贴在我的代码中,这是正确的吗? (我不知道应该怎么在这里工作……)
primes = tuple(n for n in range(1,10**6) if is_prime(n)==True)
count_best = 0
##http://docs.python.org/release/2.3.5/lib/itertools-example.html:
## Slightly modified (first for loop)
from itertools import islice
def window(seq):
for n in range(2,len(seq) + 1):
it = iter(seq)
result = tuple(islice(it,n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
def memoize(function):
cache = {}
def decorated_function(*args):
if args in cache:
return cache[args]
else:
val = function(*args)
cache[args] = val
return val
return decorated_function
@memoize
def find_lin_comb(prime):
global count_best
for windows in window(primes[0 : primes.index(prime)]):
if sum(windows) == prime and len(windows) > count_best:
count_best = len(windows)
print('Prime: ',prime,'Terms: ',count_best)
##Find them:
for x in primes[::-1]: find_lin_comb(x)
(顺便说一句,素数的元组是“正常”快速生成的)
所有的输入都很受欢迎,我只是一个业余爱好程序员,所以请不要对我有所了解.
谢谢!