Finding primes using a list

I tried to generate all primes ranging from x to y. First I tried a simple example: range(10,11) , which means to check if 10 is a prime:
Here is my code:

 prime_list = [x for x in range(10, 11) for y in range(2,x) if x % x == 0 and x % 1 == 0 and x % y != 0] 

I know that in this article there is no way to specify the expression that x%y != 0 should be checked for all y in range (2,x) and return true if and only if everyone has met this.

How do we do this?

+6
source share
5 answers

Use all to check all items (2 to x-1):

 >>> [x for x in range(2, 20) if all(x % y != 0 for y in range(2, x))] [2, 3, 5, 7, 11, 13, 17, 19] 
+16
source

Filter version:

 filter(lambda x:all(x % y != 0 for y in range(2, x)), range(2, 13)) 
+1
source

A program for finding primes in a given range using lists:

 min = 10 max = 100 primes = [num for num in range(min,max) if 0 not in [num%i for i in range(2,int(num/2)+1)]] print (primes) 
+1
source

One way to use a set of concepts could be

 list(set(range(2,11)) - {x for x in range(11) for y in range(2,x) if x%y == 0}) 
0
source
Answer to

@falsetru is correct. But you should also pay attention to optimized code. As someone said in the comments in Kasra, reply

 In [227]: %timeit [x for x in range(4, 1000) if all(x % y != 0 for y in range(2, int(m.sqrt(x)) + 1))] 100 loops, best of 3: 2.08 ms per loop In [228]: %timeit [x for x in range(4, 1000) if all(x % y != 0 for y in range(2, int(m.sqrt(x)) + 1))] 100 loops, best of 3: 2.09 ms per loop In [229]: %timeit [x for x in range(4, 1000) if all(x % y != 0 for y in range(2, x-1))] 100 loops, best of 3: 10.4 ms per loop In [230]: %timeit [x for x in range(4, 1000) if all(x % y != 0 for y in range(2, x-1))] 100 loops, best of 3: 10.3 ms per loop 
0
source

Source: https://habr.com/ru/post/989726/


All Articles