Consecutive prime sum

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?


Idea

Naive solution.

Get all primes, use 'slice window' model to check consecutive prime sum.


In [1]:
from math import sqrt
In [2]:
def is_prime(n):
    return n % 2 != 0 and all((n % d for d in range(3, int(sqrt(n))+1, 2)))
In [3]:
def generate_primes(bound):
    yield 2
    n = 3
    while n < bound:
        if is_prime(n):
            yield n
        n += 2
In [4]:
list(generate_primes(20))
Out[4]:
[2, 3, 5, 7, 11, 13, 17, 19]
In [5]:
def get_max_length(primes, bound):
    s = 0
    for i, p in enumerate(primes, 1):
        s += p
        if s > bound:
            return i
In [6]:
def solve(bound):
    all_primes = list(generate_primes(bound))
    max_length = get_max_length(all_primes, bound)
    for length in range(max_length, 0, -1):
        for start_index in range(0, len(all_primes)-length+1):
            s = sum(all_primes[start_index: start_index+length])
            if s > bound:
                break
            if is_prime(s):
                return s
In [7]:
solve(100)
Out[7]:
41
In [8]:
solve(1000)
Out[8]:
953
In [9]:
solve(1e6)
Out[9]:
997651