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?
In [1]:
def primes_less_than_n(n):
""" Returns a list of primes < n """
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
max_num_digits = 6
primes = primes_less_than_n((10**max_num_digits+1)-1)
print len(primes)
s_primes = set(primes)
def is_prime(p):
return p in s_primes
In [2]:
M = 10**max_num_digits
for num_terms in range(1,550):
for s in range(len(primes)-num_terms):
sm = sum(primes[s:s+num_terms])
if is_prime(sm):
print num_terms, sm
break
if sm > M:
break
In [ ]: