python - 是否有用于列出素数的 Python 库?

标签 python

有没有库函数可以在Python中(按顺序)枚举素数?

我发现了这个问题 Fastest way to list all primes below N但我宁愿使用别人可靠的库也不愿使用自己的库。我很乐意做 import math;对于 math.primes 中的 n:

最佳答案

SymPy是另一种选择。它是一个用于符号数学的 Python 库。它为 prime 提供了多种功能。

isprime(n)              # Test if n is a prime number (True) or not (False).

primerange(a, b)        # Generate a list of all prime numbers in the range [a, b).
randprime(a, b)         # Return a random prime number in the range [a, b).
primepi(n)              # Return the number of prime numbers less than or equal to n.

prime(nth)              # Return the nth prime, with the primes indexed as prime(1) = 2. The nth prime is approximately n*log(n) and can never be larger than 2**n.
prevprime(n, ith=1)     # Return the largest prime smaller than n
nextprime(n)            # Return the ith prime greater than n

sieve.primerange(a, b)  # Generate all prime numbers in the range [a, b), implemented as a dynamically growing sieve of Eratosthenes. 

这里有一些例子。

>>> import sympy
>>> 
>>> sympy.isprime(5)
True
>>> list(sympy.primerange(0, 100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>> sympy.randprime(0, 100)
83
>>> sympy.randprime(0, 100)
41
>>> sympy.prime(3)
5
>>> sympy.prevprime(50)
47
>>> sympy.nextprime(50)
53
>>> list(sympy.sieve.primerange(0, 100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

关于python - 是否有用于列出素数的 Python 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13326673/

相关文章:

python - 属性错误: 'NoneType' object has no attribute 'actions_with_auth_user_as_actor'

python - python函数的签名是什么

python - 尝试使用 pandas 进行 pytest 测试时出现 Keyerror

Python 关键字参数解包并返回字典

python - 如何在 Python 中渲染 3D 表面

python - appengine 数据存储多个 "puts"事务性能

python - Matplotlib 自定义图例以显示正方形而不是矩形

Python 惰性求值器

python - 如何在 Pyqt4 中设置 QTableView 标题名称

python - Pytorch:为什么 print(model) 不显示激活函数?