Skip to content
Advertisement

Is there a Python library to list primes?

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

>>> from primesieve import *

# Generate a list of the primes below 40
>>> generate_primes(40)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]

# Generate a list of the primes between 100 and 120
>>> generate_primes(100, 120)
[101, 103, 107, 109, 113]

# Generate a list of the first 10 primes
>>> generate_n_primes(10)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

# Generate a list of the first 10 starting at 1000
>>> generate_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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement