简体   繁体   English

Python函数查找素数

[英]Python function to find prime numbers

This is not about finding the prime numbers, it is about how do I transfer the code into a function. 这与查找素数无关,而是与如何将代码转换为函数有关。

so I have this codes to help me to print the prime numbers from 2-100: 所以我有以下代码可以帮助我打印2-100之间的质数:

pnumber = [x for x in range(2, 101) if all(x % i for i in range(2, x))]
print(pnumber)

If I def this as a function, to find the prime numbers in a range: 如果我将此定义为一个函数,则要找到一个范围内的质数:

 def p_number(a, b):
     pnumber = [x for x in range(a, b+1) if all(x % i for i in range(2, b))]
     print(pnumber)

 p_number(2, 100)

You can see that I use a to replace 2, and b to replace 100, and change the codes accordingly. 您可以看到我用a代替2,用b代替100,并相应地更改了代码。 But somehow, this won't work, it will output an empty list. 但是以某种方式,这将行不通,它将输出一个空列表。

I wonder why? 我想知道为什么?

Mind that if you use the upperbound b in the check: 请注意,如果您在检查中使用上限 b

all(x % i for i in range(2, b))

this will include all prime numbers up to b . 这将包括所有不超过b质数 So 2 , 3 , 5 , etc. are also part of range(2, b) (given b is large enough). 所以235 ,等也的一部分range(2, b)给定的b是足够大)。 So that means that if we test for instance whether 3 is a prime, we will check for i = 3 , and 3 % 3 is 0 , so that will fail. 因此,这意味着如果我们测试3是否为素数,则将检查i = 3 ,并且3 % 30 ,这样将失败。

Furthermore it will have a bad impact on performance. 此外,它将对性能产生不利影响。 The idea of a prime test is to check all numbers up to but excluding the number. 素数测试的想法是检查所有数字,但不包括数字。 So a quick fix is: 因此,一个快速的解决方法是:

def p_number(a, b):
    pnumber = [x for x in range(a, b+1) if all(x % i for i in range(2, x))]
    print(pnumber)

We can easily boost it further by using int(sqrt(x))+1 instead of x : 我们可以使用int(sqrt(x))+1而不是x轻松地进一步增强它:

from math import sqrt

def p_number(a, b):
    pnumber = [x for x in range(a, b+1) if all(x % i for i in range(2, int(sqrt(x))+1))]
    print(pnumber)

We can boost it further, for instance by only evaluating odd numbers (and add 2 to the result). 我们可以进一步提高它,例如,仅评估奇数(并将结果加2)。 But using sqrt will usually already result in a significant speedup. 但是使用sqrt通常已经可以显着提高速度。

Change your function to - 将您的功能更改为-

def p_number(a, b):
     pnumber = [x for x in range(a, b + 1) if all(x % i for i in range(a, x))]
     print(pnumber)

If you notice, you were iterating i from 2 to b, and not from 2 to x which is why you were getting an empty list. 如果您注意到,您将i从2迭代到b,而不是从2迭代到x,这就是为什么您得到一个空列表的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM