# EulerProblem050

# Consecutive prime sum (Euler Problem 50)¶

Back to overview.

https://projecteuler.net/problem=50

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 sieve_of_eratosthenes(number):
        primes = []
        prospects = [n for n in range(2, number)]
        while prospects:
            p = prospects[0]
            prospects = [x for x in prospects if x % p != 0]
            primes.append(p)
            if p * p > number:
                break
        return primes + prospects

In [2]:

    def find_max_series(start_index, series_list, series_set):
        series_max = series_list[-1]
        total_max = 0
        total = 0
        for i in range(start_index, len(series_list)):
            total = total + series_list[i]
            if total in series_set:
                length = i - start_index + 1
                total_max = total
            if total > series_max:
                return (length, total_max)

In [3]:

    n_max = 100
    ps = sieve_of_eratosthenes(n_max)
    ps_set = set(ps)
    ps_max = max(ps)
    s = max([x for x in [find_max_series(i, ps, ps_set) for i in range(0, n_max)] if x])
    print(s)
    assert(s[1] == 41)

    (6, 41)

In [4]:

    n_max = 1000
    ps = sieve_of_eratosthenes(n_max)
    ps_set = set(ps)
    ps_max = max(ps)
    s = max([x for x in [find_max_series(i, ps, ps_set) for i in range(0, n_max)] if x])
    print(s)
    assert(s[0] == 21)
    assert(s[1] == 953)

    (21, 953)

In [5]:

    n_max = 1000000
    ps = sieve_of_eratosthenes(n_max)
    ps_set = set(ps)
    ps_max = max(ps)
    s = max([x for x in [find_max_series(i, ps, ps_set) for i in range(0, n_max)] if x])
    print(s)
    assert(s[1] == 997651)
    print(s[1])

    (543, 997651)
    997651