0
votes

Heres the code I'm trying to understand:

The code is the implementation of Sieve of Erastothenes. If I understand it correctly, then up to line 8, the code creates a list of prime numbers up to N and the list is a boolean list where True - prime; False - non-prime; and the index number matches with the number we output.

My question is: For lines 9-13 does the script "rewrite" the primes (which are just True values) with both the index and the boolean value in a new list in order for us to print them at the end? Also, if primes is a boolean list, why python prints the index values at the end instead of just a bunch of True arguments?

Update: I got it, thanks guys! range is a set of integers from 2 - n+1, hence i is integer as well, thats why I get integers in the primes string. For some reason I was thinking of range as list1 initialy

def sita(N):
    list1 = [True for _ in range(N + 1)]
    list1[0:1] = [False, False]
    for start in range(2, N + 1):
        if list1[start]:
            for i in range(2 * start, N + 1, start):
                list1[i] = False
    primes = []  #create empty list
    for i in range(2, N + 1):
        if list1[i]:
            primes.append(i)
    return primes
print(sita(int(input("Dati un numar N: "))))
2
primes is not a list of booleans. That's the entire point of the second loop. Can you clarify what you mean by "rewrite with both the index and boolean value"?MisterMiyagi
I mean, it takes the values which are True and rewrites them in a new list with the same old index and valueFl1pp

2 Answers

0
votes

Your loop, for i in range(2, N + 1): is looping over the actual indices. It tests the boolean value in list1[i], but only stores the index. The boolean value (list1[i]) need not be written; the mere fact that you appended i indicates that the test passed, and i is known to correspond to a prime number. Since primes is built from scratch, it contains no booleans at all, just the various i values (tested and found prime) appended to it in the final loop.

0
votes

primes.append(i) only appends its argument, i. There is no magic that would additionally append anything else to the list.

In your code, there are two separate, independent lists: list1 and primes:

  • The first contains a boolean for each non-negative integer.

  • The second contains those integers for which list1 contained True at the end of the first loop (this is what the if list1[i] check does).