The prime 41, can be written as the sum of six consecutive primes:
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?
Naive solution.
Get all primes, use 'slice window' model to check consecutive prime sum.
from math import sqrt
def is_prime(n):
return n % 2 != 0 and all((n % d for d in range(3, int(sqrt(n))+1, 2)))
def generate_primes(bound):
yield 2
n = 3
while n < bound:
if is_prime(n):
yield n
n += 2
list(generate_primes(20))
def get_max_length(primes, bound):
s = 0
for i, p in enumerate(primes, 1):
s += p
if s > bound:
return i
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
solve(100)
solve(1000)
solve(1e6)