质数判断
Prime numbers have always been very mysterious to me, because there isn’t a very clear pattern to them. Sure there are rules you can define to test for them very easily, but conceptually, it doesn’t seem to correspond to anything in real life (not to me anyway), they almost seemed like independent vectors of some sorts, maybe a spanning set for the positive integers…
质数一直对我来说一直很神秘,因为它们没有一个非常清晰的模式。 当然,您可以定义一些规则来对其进行轻松测试,但是从概念上讲,它似乎并不对应于现实生活中的任何内容(无论如何对我而言),它们几乎就像某种形式的独立矢量,也许是跨越集对于正整数...
Anyways, here is a quick way to test for prime numbers that can be implemented off-hand. There are much more complicated algorithms for testing primality, maybe I’ll cover them in a different story.
无论如何,这是一种测试可以立即实现的质数的快速方法。 有很多复杂的算法可以测试素数,也许我会在另一个故事中介绍它们。
First version is very simple. To test primality of n, loop through every positive integer from 2 to n-1, if n is divisible by any of those numbers, then it’s not a prime, otherwise it is:
第一个版本非常简单。 要测试n的素数,请遍历从2到n-1的每个正整数,如果n可被这些数中的任何一个整除,则它不是素数,否则为:
def is_prime(n): for i in range(2, n): if n % i == 0: return False return TrueWell, the complexity of this algorithm is obviously O(n), not bad for most practical purposes. But there is a very simple shortcut. Let’s take 16 for example, if you test number by number, 2, 3, 4, … you’ll realize that for 2 to divide 16, you’ll need 8, for 3 to divide 16, you’ll need a number around 5~6, and for 4, well, you’ll need 4, since 4 is square root of 16. So you see, once you’ve reached 4, the square root of 16, you don’t need to test any further, because any number greater is paired with a number you have already tested, if there is a pair.
好吧,该算法的复杂性显然是O(n) ,对于大多数实际目的而言还不错。 但是有一个非常简单的捷径。 让我们以16为例,如果您按数字测试数字2、3、4 ...,您将认识到,将2除以16,您将需要8,将3除以16,您将需要一个数字5〜6,对于4,好吧,您将需要4,因为4是16的平方根。因此,您可以看到,一旦达到4,即16的平方根,则无需进一步测试。 ,因为任何较大的数字都会与您已经测试过的数字配对(如果有的话)。
Therefore, you can speed up the process with this:
因此,您可以使用以下方法加快处理过程:
def is_prime(n): for i in range(2, int(np.sqrt(n)) + 1): if n % i == 0: return False return TrueWell, this is of complexity O(sqrt(n)), much better.
好吧,这是复杂度O(sqrt(n)) ,好得多。
But there are actually even better ones that are O(log(n)):
但是实际上甚至还有更好的O(log(n)) :
Hopefully I’ll get to show them later :)
希望我以后再给他们看:)
As an excuse to show pretty pics, this is a graph of performances of various complexity:
作为展示漂亮图片的借口,这是各种复杂性能的图表:
And yes, you do want O(log(n)).
是的,您确实想要O(log(n)) 。
Did you know that we have three publications and a YouTube channel? Find links to everything at plainenglish.io!
您知道我们有三个出版物和一个YouTube频道吗? 在plainenglish.io上找到所有内容的链接!
翻译自: https://medium.com/python-in-plain-english/prime-numbers-cecdfcde33d2
质数判断
