欧拉项目010:2000000以内的素数和

Summation of primes

Problem 10

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

还是使用Sieve of Eratosthenes 算法

我的python代码例如以下:


#coding:utf-8
#从2到sqrt(n)
# 不用全部的都用遍历。从i**2,步长为i,i*2,i*3肯定都不是质素。
# 从i*i開始,仅仅要是i>2,是由于i*2,i*3已经被測试过,不用在计算了
from math import sqrt
def primesieve(n):
    l=range(n)
    l[1]=0
    for i in range(2,int(sqrt(n))):
        if l[i]:
            l[i**2::i]=[0]*((n-1-i**2)//i+1)
    return [x for x in l if x]
print sum(primesieve(2000000))


原文地址:https://www.cnblogs.com/mengfanrong/p/5175092.html