pythondebuggingmath

Incorrect output Project Euler #50


Project Euler problem 50 reads as follows:

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 my approach I pregenerate a list of primes using sieve of eratosthenes, then in the function itself I keep adding succeeding elements of my prime number list and each time i do that I check if the sum itself is prime and if it is I keep track of it as the biggest one and return it. Well that should work i guess ? Obviously the answer is incorrect, but the interesting thing is that when i change the sieve to generate primes below 100000 it doesn't give an index error but gives another result.

from algorithms import gen_primes

primes = [i for i in gen_primes(1000000)]


def main(n):
    idx, total, maximum = 0, 0, 0
    while total < n:
        total += primes[idx]
        idx += 1
        if total in primes:
            maximum = total
    return maximum


print(main(1000000))

Solution

  • Your program doesn't solve the general problem: you always start your list of consecutive primes at the lowest, 2. Thus, what you return is the longest consecutive list starting at 2*, rather than any consecutive list of primes.

    In short, you need another loop ...

    start_idx = 0
    while start_idx < len(primes) and best_len*primes[start_idx] < n:
        # find longest list starting at primes[start_idx]
        start_idx += 1
    

    In case it's any help, the successful sequence begins between 1500 and 2000.