Sieve due to confusion with the introduction of Eratosthenes

I wanted to first indicate that I am new to python, and that I am kind to anyone who can explain this to me clearly and completely.

I looked at the code found at the link below:

http://rosettacode.org/wiki/Sieve_of_Eratosthenes#Python

I just started to understand iterators, generators, and the yield command, but I don’t understand how the code works to implement the set.

def eratosthenes2(n):
    multiples = set()
    for i in range(2, n+1):
        if i not in multiples:
            yield i
            multiples.update(range(i*i, n+1, i))

I find it difficult to understand what the last line in this function does.

Also, can someone explain to me why this implementation is O (log (n)) time?

+4
source share
2 answers

range(i, j, k) i j (j , j-1) k ( - 1). range(2, 10, 2) [2, 4, 6, 8].

, i i 2 n multiples. i 2 i - ( ), i multiples i & times; i. : i , c & times; i c, 1 < c < i, . n+1, , (1 , ). , , i .

O (log (n)) , . O (n), n -1 ( 2 n). , O (1) , Python -. list of n bool s, .

+1

:

multiples.update(range(i*i, n+1, i))

i i n multiples. i i.

, O (log (n)), , , , - O (log (n)) vs list O (n). , O (1) O (n)

+1

Source: https://habr.com/ru/post/1612343/


All Articles