O
O
Oli2021-12-07 19:33:48
Python
Oli, 2021-12-07 19:33:48

How to find prime numbers in a range?

Hello! Can you tell me how you can use the sieve of Eratosthenes to find prime numbers in a range?

def sieve(n):
    prime = list(range(n + 1))
    prime[1] = 0
    i = 2
    while i * i <= n:
        if prime[i]:
            j = i * i
            while j <= n:
                prime[j] = 0
                j += i
        i += 1
    return prime

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-12-07
@Vindicar

The sieve of Eratosthenes involves the removal of elements that are multiples of the next prime number.
Those. processed 2 - cross out every 2nd element. Processed 3 - every third, and so on.
From here we get the following.
We have the original list of elements. At each step, when we test k, we throw out all multiples of k except for k itself.
numbers = list(range(2, n+1))

numbers = [ x for x in numbers if x % k != 0 or x == k]

How do we choose k? We just go through the list of numbers from the beginning. All elements at the beginning of the list will always be prime, since 2 is prime, and all subsequent composite elements will be thrown out in one of the iterations
i = 0
while i < len(numbers):
  k = numbers[i]
  numbers = [ x for x in numbers if x % k != 0 or x == k ]
  i += 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question