Answer the question
In order to leave comments, you need to log in
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
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]
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 questionAsk a Question
731 491 924 answers to any question