def partitionFnGen(): # partition function over the primes mem = [[1]] def get(n, i): # in how many ways can n be written using primes of index >= i if n == 0: return 1 if n < primes.get(i): return 0 return mem[n][i] for n in count(1): parts = takewhile(lambda p: p <= n, primes.gen()) decomp = [get(n - p, i) for i, p in enumerate(parts)] mem.append(list(reversed(list(runningSum(reversed(decomp)))))) yield get(n, 0)
def main(lim): # trick: compute the running sum first so we can compute the sum of primes i to j in constant time sums = list(runningSum(takewhile(lambda p: p <= lim, primes.gen()))) size = len(sums) # find max length length = 0 while sums[length + 1] < lim: length += 1 # return the first prime sum while length > 0: for start in range(size - length): total = sums[start + length] - sums[start] if total >= lim: # sums are in increasing order break if primes.isPrime(total): return total length -= 1