Back to Project Euler

Previous Problem Next Problem

Problem 50: 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?

Solution

Let \(p_1, p_2, \ldots\) be the prime numbers in order, and let \(S_{n,k} = \sum_{i=n}^{n+k-1} p_i\). The objective is to find \(S_{n,k} < 10^6\) such that \(S_{n,k}\) is prime and \(n\) is maximized. Thus, it makes sense to iterate over \(n\) decreasing in the outer loop, and iterate over \(k\) increasing in the inner loop. The starting value of \(n\) will be the largest such value for which \(S_{n,1} < 10^6\). For \(k > 1\), note that \(S_{n,k} = S_{n,k-1} + p_{n+k-1} - p_{k-1}\).

Python Code

from sympy import primerange, isprime
def p50(C = 10**6):
	plist = list(primerange(C))
	n_start, S_start = 0, 0
	while S_start < C:
		S_start += plist[n_start]
		n_start += 1
	for n in range(n_start - 1, 0, -1):
		S_start -= plist[n]
		S = S_start
		k = 0
		while S < C:
			if isprime(S):
				return S
			S += plist[n+k] - plist[k]
			k += 1

Previous Problem Next Problem

Back to Project Euler