eratosthenes_用python中的eratosthenes筛子查找素数

本文介绍了如何使用Python实现埃拉托斯特尼筛法,这是一种寻找素数的有效算法。通过该方法,可以高效地找出指定范围内的所有素数。
摘要由CSDN通过智能技术生成

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:

总结过程:

  1. Create a list of integers from 2 to the highest number you want to check, marking them all as prime

    创建一个从2到要检查的最大数字的整数列表,并将它们全部标记为素数
  2. Initialize a variable p to 2 (the lowest prime)

    将变量p初始化为2(最低质数)

  3. Mark all multiples of p as composite (ie. non-prime)

    p的所有倍数标记为复合值(即非质数)

  4. Set p to the next number marked as prime

    p设置为标记为质数的下一个数字

  5. 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的简单直接实现中。

编写代码 (Writing the Code)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值