Project Euler #10 (Python)

前端 未结 9 1437
情深已故
情深已故 2021-01-22 07:27

Why is my algorithm for finding the sum of all prime numbers below 2 million so slow? I\'m a fairly beginner programmer and this is what I came up with for finding the solution:

9条回答
  •  既然无缘
    2021-01-22 08:00

    Your algorithm uses trial division, which is very slow. A better algorithm uses the Sieve of Eratosthenes:

    def sumPrimes(n):
        sum, sieve = 0, [True] * n
        for p in range(2, n):
            if sieve[p]:
                sum += p
                for i in range(p*p, n, p):
                    sieve[i] = False
        return sum
    
    print sumPrimes(2000000)
    

    That should run in less than a second. If you're interested in programming with prime numbers, I modestly recommend this essay at my blog.

提交回复
热议问题