Вопрос

I am working on an assignment in beginning Python calling for a list of primes less then 100 using set comprehension. I can generate non primes using

nonPrime = { x for x in range(2, 100) for y in range(2, x) if x % y == 0 }

This effectively returns all non prime numbers but I can not find a way other than to Excursive Or this set with a set of all numbers from 2 to 100 to get a set of prime numbers. Is there a way that I can get the opposite of this set within the same set comprehension?

Это было полезно?

Решение

This is not the most efficient algorithm, but to implement it:

prime = {x for x in range(2, 100) if all(x % y != 0 for y in range(2, x))}

Or, equivalently:

prime = {x for x in range(2, 100) if not any(x % y == 0 for y in range(2, x))}

For one simple refinement, you can stop checking for possible factors once you've passed the square root of x:

prime = {x for x in range(2, 100) if all(x % y != 0 for y in range(2, int(math.floor(math.sqrt(x))) + 1))}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top