Lua bindings for primesieve, a library for fast prime number generation
I originally wrote this to faciliate some just intonation work in Pure Data without requiring a hard-coded prime limit. I don't need it for myself anymore but I sought to make it feature complete and analogous to the library's C++ API. Currently supports Lua >= 5.3. 5.1 compatibility is on the agenda. Pull requests welcome.
The primesieve documentation only outlines the following functions. There are more in the library that also have bindings here; their usage should be self-explanatory and can be found by reading the source.
The arrays generated by primes()
and n_primes()
are a userdata
type that can be indexed like normal Lua arrays and have a functional length (#
) operator.
ps = require 'primesieve'
ps.primes(max) -- generate array of primes <= 'max'
ps.primes(min, max) -- generate array of primes between 'min' and 'max'
ps.n_primes(n) -- generate array of 'n' primes
ps.n_primes(n, min) -- generate array of 'n' primes >= 'min'
ps.nth_prime(n) -- find the 'n'th prime
ps.nth_prime(n, min) -- find the 'n'th prime starting at 'min'
ps.count_primes(min, max) -- count the number of primes between 'min' and 'max'
Direct access to the iterator used to generate primes is provided by the following functions. The primesieve docs note that this is "not ideal if you are repeatedly iterating over the same primes in a loop" and recommend generating a lookup table with primes()
or n_primes()
in such cases. For more specific details, consult the original docs.
it = ps.iterator() -- constructor for the iterator class
it = ps.iterator(start) -- initializes iterator to 'start' number
it = ps.iterator(start, stop_hint) -- only buffers primes up to 'stop_hint'
it:next() -- step forward one prime
it + 1 -- same thing, but can be any number of iterations
it:prev() -- step backward one prime
it - 1 -- see above
it:jump_to(start)
it:jump_to(start, stop_hint)
it:clear() -- resets iterator to 0
print(it) -- __tostring metamethod will print either current prime or 'nil' if iterator holds a null pointer
The simplest way is to use LuaRocks to build, install, and manage your LUA_CPATH
. Otherwise you can build manually with CMake:
git clone https://github.com/kennypm/lua-primesieve/
cd lua-primesieve
mkdir build
cd build
cmake ..
make