2013-04-17 14:34:39 +08:00

43 lines
726 B
Python

''' The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million. '''
def makeP(x):
P = [3]
p = [3]
n = 5
while n < x:
for i in p:
if n % i == 0:
break
else:
P.append(n)
n += 2
while p[-1] ** 2 < n:
p.append(P[len(p)])
return P
maxx = 2000000
maxxx = int(maxx ** 0.5)
prime = makeP(maxxx)
total = 2 + 3 + 5 + 7
for i in xrange(len(prime) - 1):
for x in xrange(prime[i] ** 2 + 2, prime[i + 1] ** 2, 2):
for p in prime[:i + 1]:
if x % p == 0:
break
else:
total += x
for x in xrange(prime[-1] ** 2 + 2, maxx, 2):
for p in prime:
if x % p == 0:
break
else:
total += x
print total