Sliding window calculations and memories

I am working on a Project Euler 50 issue that says:

The first 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, which adds to a prime below 100.

The longest sum of consecutive primes below one thousand, adding to the prime, contains 21 terms and is equal to 953.

What simple, less than one million can be written as the sum of the most consecutive primes?

To determine the terms in prime P (if it can be written at all as a sum of primes), I use the sliding window of all primes (in ascending order) to (but not including) P , and calculate the sum of all these windows if the sum equal to the considered number, I calculate the length of the window ...

This works fine for all 1000 primes , but for primes up to 10 ** 6 it works very slowly, so I was hoping to write it down ; when calculating the sum of the sliding windows, a lot of double work is done ... (right?)

So, I found the standard implementation of memoizaton on the network and just pasted it into my code, is that right? (I have no idea how this should work here ...)

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)

(btw, "" )

, , , , .

!

: , : http://pastebin.com/R1NpMqgb

+5
2

1000, 10 ** 6 , , ; ... (?)

, . , , 10 6.

, n n, , p_1 = 2, p_2 = 3, .... , . k - , [p_i, ..., p_j], (i,j) i < j < k. (k-1)*(k-2)/2. k n, n³/6 ( , w(i.j) n-j ). , , :

  • N = 1000 n = 168 790000 ( ).
  • N = 10**6 n = 78498 8.3*10**13 .

j-i+1 j-i+1 w(i,j), p_k k³/6, k**4/24. - 33 N = 1000, , 1.6*10**18 N = 1000000.

3.1*10**7 , ~ 3GHz, 10 17 . , , - 100 CPU- ( 10 ).

, ;)

, memoisation, , . , n³/6 , n³/6 .

  • 1: 8.3*10**13 , , .
  • 2: 8.3*10**13 memoise. , HD.

, , , , , , , .

, , 21 953.

, ? , ? ?

+3

memoize ( ). , . , ..

  • . .
  • , , .

find_lin_comb . -, , .

+1

All Articles