You are here: Home Programming Python Project Euler 010 - sum of primes

010 - sum of primes

Find the sum of all the primes below one million.

See Problem 10.

It's fairly easy to retool the solution to problem 7 to solve this:

def iter_primes ():
        # handle trivial case
        yield 2
        val = 1
        primesq_pairs = []
        while True:
                curr = None
                while (curr is None):
                        val += 2
                        curr = val
                        for prime, square in primesq_pairs:
                                if (curr < square):
                                        break
                                if (curr % prime == 0):
                                        curr = None
                                        break
                primesq_pairs.append ((curr, curr ** 2))
                yield curr


sum = 0
for x in iter_primes():
        if (x < 1000000):
                sum += x
        else:
                break
print sum

The answer is 37550402023. Execution time is 3.6s. There no way to solve this without generating (and storing) all the intermediate primes but the speed is still better than expected.

Document Actions
Visitors
Locations of visitors to this page
 
Personal tools