简体   繁体   中英

Python - Sum of primes

In this Sum of primes algo:

Let S(v,p) be the sum of integers in the range 2 to v that remain after sieving with all primes smaller or equal than p. That is S(v,p) is the sum of integers up to v that are either prime or the product of primes larger than p.

S(v,p) is equal to S(v,p−1) if p is not prime or v is smaller than p2. Otherwise (p prime, p2≤v)S(v,p) can be computed from S(v,p−1) by finding the sum of integers that are removed while sieving with p. An integer is removed in this step if it is the product of p with another integer that has no divisor smaller than p. This can be expressed as

S(v,p)=S(v,p−1)−p(S(⌊v/p⌋,p−1)−S(p−1,p−1))

def P10(n):
    sqrt = int(n**0.5)
    V = [n//i for i in range(1,sqrt+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,sqrt+1):
        if S[p] > S[p-1]:  # p is prime
            sp= S[p-1]  # sum of primes smaller than p
            p2 = p*p
            for v in V:
                if v < p2: break
                S[v] -= p*(S[v//p] - sp)

 return S[n]

I'm a bit confused in this part:

if S[p] > S[p-1]:  # p is prime

Does it mean values are accessed in S by index p ? Values of p range from 2 to sqrt, while S got it's indices from V. Won't it cause any index exception??

Thanks. *I'm a python newbie

S is a Dictionary, and is being accessed by key, using similar syntax to list-index access. The 'key' differences being that :

  1. It will return KeyError if it fails (where p is not a key in S, in this example)

  2. A specific value has been saved in S to represent p - note the colon in the constructor {i:i*(i+1)//2-1 for i in V}. The key is set to a list item in V, and the linked value is set to the result of the mathematical manipulation following it.

The curly braces {} indicate that a Dictionary is being constructed, and the colon separates key assignment from value assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM