Is there a library function that can enumerate the prime numbers (in sequence) in Python?
I found this question Fastest way to list all primes below N but I’d rather use someone else’s reliable library than roll my own. I’d be happy to do import math; for n in math.primes:
Advertisement
Answer
Since asking this question, I wrote a Python wrapper around the C++ library primesieve, which went on to be adopted by the primesieve maintainer. https://github.com/kimwalisch/primesieve-python
Install from PyPi https://pypi.org/project/primesieve/ pip install primesieve
JavaScript
x
26
26
1
>>> from primesieve import *
2
3
# Generate a list of the primes below 40
4
>>> generate_primes(40)
5
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
6
7
# Generate a list of the primes between 100 and 120
8
>>> generate_primes(100, 120)
9
[101, 103, 107, 109, 113]
10
11
# Generate a list of the first 10 primes
12
>>> generate_n_primes(10)
13
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
14
15
# Generate a list of the first 10 starting at 1000
16
>>> generate_n_primes(10, 1000)
17
[1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061]
18
19
# Get the 10th prime
20
>>> nth_prime(10)
21
29
22
23
# Count the primes below 10**9
24
>>> count_primes(10**9)
25
50847534
26