简体   繁体   中英

Can someone explain this prime list generator for me?

This is apparently a very fast prime list generator ( Fastest way to list all primes below N ), but I can't understand some parts of it, mostly because of the syntax.

def rwh_primes1(n): 
    """ Returns  a list of primes < n """
    sieve = [True] * (n/2)
    for i in xrange(3,int(n**0.5)+1,2):
        if sieve[i/2]:
            sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*i)+1)
    return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]]

Why sieve is defined as [True] (a boolean) multiplied by an integer?

What means if sieve[i/2] ?

What means sieve[i*i/2::i] , especially the ::i part?

looks like it's just array notation you're looking for.

[a] * 5 just becomes [a,a,a,a,a]

if sieve[i/2] is checking if the value of sieve at i/2 is True or False

and the :: defines the stride.

see this answer.

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