For reference (if you are here, then you are already trying to find the answer), I quote Lucy_Hedgehog (in the development team for PE):
Here is a solution that is more effective than the Eratosthenes sieve. It is derived from similar algorithms for counting strokes . the advantage is that there is no need to find all primes to find their sum.
The main idea is this: let S (v, m) be the sum of integers in the range 2..v, which remains after sifting with all strokes less than or equal to m. That is, S (v, m) is the sum of integers up to v, which are either prime or the product of primes greater than m.
S (v, p) is equal to S (v, p-1) if p is not simple or v is less than p * n. Otherwise (p prime, p * p <= v) S (v, p) can be calculated from S (v, p-1) by finding the sum of integers that are removed by sifting with p. In this step, the integer is removed if it is the product of p with another integer that does not have a divisor less than p. It can be expressed as
$ S (v, p) = S (v, p-1) - p (S (v / p, p-1) - S (p-1, p-1)). $
To implement this, you can use dynamic programming. It is enough to calculate S (v, p) for all natural numbers v, which are representable as (n / k) for some integer k and all $ p \ leq \ sqrt v $.
def P10(n): r = int(n**0.5) assert r*r <= n and (r+1)**2 > n V = [n//i for i in range(1,r+1)] V += list(range(V[-1]-1,0,-1)) S = {i:i*(i+1)//2-1 for i in V} for p in range(2,r+1): if S[p] > S[p-1]:
The complexity of this algorithm is $ O (n ^ {0.75}) $ and needs 9 ms to find a solution.