eratosthenes
Prime numbers have been understood at least since the Ancient Greeks, and possibly since the Ancient Egyptians. In modern times their study has intensified greatly due to their usefulness, notably in encryption, and because computers enable them to be calculated to a massively higher level than could be done by hand.
质数至少自古希腊人以来就已被理解,并且可能自古埃及人以来就已被理解。 在现代,由于其实用性,特别是在加密方面,并且由于计算机使它们的计算量大大超过了手工计算的水平,因此对它们的研究大大增强。
The best know (and according to Wikipedia still the most widely used) method for identifying them is the Sieve of Eratosthenes, which I will implement here in Python.
识别它们的最好的方法(据Wikipedia仍是最广泛使用的)是Eratosthenes的筛网,我将在这里用Python来实现。
Eratosthenes筛 (The Sieve of Eratosthenes)
The algorithm is described in full on Wikipedia, and you might like to take a look at the article.
该算法已在Wikipedia上进行了完整描述,您可能想看看该文章 。
To summarize the process:
总结过程:
- Create a list of integers from 2 to the highest number you want to check, marking them all as prime 创建一个从2到要检查的最大数字的整数列表,并将它们全部标记为素数
Initialize a variable p to 2 (the lowest prime)
将变量p初始化为2(最低质数)
Mark all multiples of p as composite (ie. non-prime)
将p的所有倍数标记为复合值(即非质数)
Set p to the next number marked as prime
将p设置为标记为质数的下一个数字
- Repeat 3 and 4 until no subsequent primes are found. 重复3和4,直到找不到后续的质数。
The algorithm as it stands has some glaring inefficiencies and the Wikipedia article cited above does include some refinements and alternatives. Nevertheless, let’s get stuck into a simple and straightforward implementation in Python.
目前的算法效率低下,上面引用的Wikipedia文章确实包含一些改进和替代方案。 尽管如此,让我们陷入Python的简单直接实现中。