在 Python 中迭代素数
问题:
使用 Python 你想遍历连续的素数
解决方案
你可以使用 gmpy2 的 next_prime() 来做到这一点:
primes_example.py
import gmpy2
def primes(start=2):
n = start
while True:
n = gmpy2.next_prime(n)
yield n
# 用法示例 1
for prime in primes():
print(prime)
# 用法示例 2
for i, prime in enumerate(primes()):
print("第 {} 个素数是 {}".format(i, prime))Check out similar posts by category:
Mathematics, Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow