Skip to main content
1 of 3

Project Euler Problem #50 Consecutive Prime Sums

At the moment my code runs for over 200 seconds and was wondering how I can find a way to bring that down by a large amount. I have tried optimising it as much as I can and added an extra if statement, if(subSum < 1000000): to reduce the need to see if subSum is a prime. Here is my code at the moment:

def sieve(num):
    primes = []
    import math
    for i in range(num):
        primes.append(True)
    j = 1
    while(j<(math.sqrt(num)+1)):
        k = (j+1)*2
        while(k<(num+1)):
            primes[k-1] = False
            k+=(j+1)
        j+=1
    primes[0] = False
    prime = []
    for a in range(num):
        if(primes[a] == True):
            prime.append(a+1)
    return prime

primes = sieve(1000000)
count = 1
high = 0
length = len(primes)
while count <= length: 
    i = 0
    while(i<(length-count)):
        sub = primes[i:i+count]
        subSum = sum(sub)
        if(subSum < 1000000):
            if(subSum in primes):
                if(subSum>high):
                    high = subSum
                break
            else: 
                i+=1
        else:
            break
    count += 1
print(high)

Thanks for any help.