Find all primes from 2 to n using a sieve of Eratosthenes

I have a word problem that I'm trying to solve, but I'm stuck on a key part.

Convert the following English description to Python code.

Initialize n to be 100. Initialize the numbers as a list of numbers from 2 to n but not including n . With the results starting with an empty list, repeat the following if the numbers contain any numbers.

  • Add the first number to the numbers at the end of the results .

  • Remove each number from the numbers that is evenly divided by (has no remainder when divided by) the number you just added to the results .. p>

How long is the result?

When n is 100, the length of the results is 25.

Until now, I realized that I need to install n = 100and range(2, 100), results = []and that the result will be the situation with the addition, as in results.append(numbers[]), but I have a mental block defining the key "Delete each number in the numbers that are divided by the number added to the results."

====== in a couple of minutes =======

As Michael0x2a said, this is a problem when I need to implement an algorithm that finds all primes from 2 to n using an Eratosthenes sieve.

, .

.

+4
2
n = 100
numbers = range(2,100)
results = []
while len(numbers) > 0:
    results.append(numbers[0])
    numbers = [number for number in numbers if number % results[-1] != 0]
print len(results)
+3

:

.

... :

results.append(numbers[])

first , .

:

numbers[0] ## would be the first "number" in numbers

, :

, " , , ".

... - , , , modulo:

some_number % some_other_number

, .

+2

All Articles