It turns out the Sieve of Eratosthenes is fairly simple to implement in Python by using correct slicing. So you can use it to recover the n first primes and sum them.
It was pointed out in Joran Beasley's answer that an upper bound for the n-th prime is n * ln(n) + n * ln( ln(n) )
, which we can use and then discrard the extra primes. Note that this bound does not work for n smaller than 6.
from math import log
def sum_n_primes(n):
# Calculate the upper bound
upper = int(n * ( log(n) + log(log(n))))
# Prepare our Sieve, for readability we make index match the number by adding 0 and 1
primes = [False] * 2 + [True] * (upper - 1)
# Remove non-primes
for x in range(2, int(upper**(1/2) + 1)):
if primes[x]:
primes[2*x::x] = [False] * (upper // x - 1) # Replace // by / in Python2
# Sum the n first primes
return sum([x for x, is_prime in enumerate(primes) if is_prime][:n])
It takes a few seconds, but outputs that the sum of the 10,000,000 first primes is 870530414842019
.
If you need n to be any higher, one solution would be to improve your upper bound.