Finding prime numbers using list comprehention

后端 未结 5 573
迷失自我
迷失自我 2020-12-16 17:55

I was trying to generate all prime numbers in range x to y. I tried simple example first: range(10,11) which means to check if 10 is a prime number:
Here is

5条回答
  •  攒了一身酷
    2020-12-16 19:01

    @falsetru's answer is correct. But also, attention should be paid to optimized code. As someone said in the the comments in Kasra's answer

    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
    

提交回复
热议问题