快速素数发生器。PrimeScript C/C++库的Python绑定
primesieve的Python项目详细描述
PrimeseefPython
python绑定为primesievec++ 图书馆。
比任何纯python代码都能更快地生成数量级的primes!
功能:
- 获取素数列表
- 使用少量内存在素数上迭代
- 找到第n个素数
- 计数/打印素数和prime k-tuplets
- 多线程,用于计算素数和查找第n个素数
- Numpy支持
先决条件
您需要在所有OSES上安装除Windows以外的C++编译器。
# Ubuntu/Debian sudo apt install g++ python-dev # Fedora sudo dnf install gcc-c++ python-devel # macOS xcode-select --install
安装
pip install primesieve
用法示例
>>>fromprimesieveimport*# Get a list of the primes <= 40>>>primes(40)[2,3,5,7,11,13,17,19,23,29,31,37]# Get a list of the primes between 100 and 120>>>primes(100,120)[101,103,107,109,113]# Get a list of the first 10 primes>>>n_primes(10)[2,3,5,7,11,13,17,19,23,29]# Get a list of the first 10 primes >= 1000>>>n_primes(10,1000)[1009,1013,1019,1021,1031,1033,1039,1049,1051,1061]# Get the 10th prime>>>nth_prime(10)29# Count the primes below 10**9>>>count_primes(10**9)50847534
这是一张list of all available functions。
在素数上迭代
而不是生成一个大的素数列表然后做些什么 对于素数,也可以简单地在素数上迭代。 它占用的内存更少。
>>>importprimesieveit=primesieve.Iterator()prime=it.next_prime()# Iterate over the primes below 10000whileprime<10000:printprimeprime=it.next_prime()# Set iterator start number to 100it.skipto(100)prime=it.prev_prime()# Iterate backwards over the primes below 100whileprime>0:printprimeprime=it.prev_prime()
numpy支持
使用primesieve.numpy
模块可以生成
使用^ {STR 1 } $原生C++性能的素数!
相比之下,primesieve
模块生成一个素数列表
大约慢7倍,主要是因为C++素数的转换。
数组进入python列表的速度非常慢。
>>>fromprimesieve.numpyimport*# Generate a numpy array with the primes below 100>>>primes(100)array([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])# Generate a numpy array with the first 100 primes>>>n_primes(100)array([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,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541])
开发
您需要安装一个C++编译器,请参阅Prerequisites。
# Install prerequisites pip install cython pytest numpy # Clone repository git clone --recursive https://github.com/hickford/primesieve-python cd primesieve-python # Build and install primesieve-python pip install . --upgrade # Run tests py.test