const-primes
Generate and work with prime numbers in const contexts.
This crate lets you for example pre-compute prime numbers at compile time, store them in the binary, and use them later for related computations, or check whether a number is prime in a const function.
no_std
compatible when the serde
feature is disabled.
This version of the crate supports Rust versions 1.81.0 and up, while versions 0.8.7 and older support Rust versions 1.67.1 and up.
Example: generate primes at compile time and use them for related computations
The struct Primes
is a wrapper around an array of primes generated by a
segmented sieve of Eratosthenes
and can be used as a cache of prime numbers for related computations:
// The first 100 primes
const CACHE: = new;
// Primality testing
const CHECK_42: = CACHE.is_prime;
const CHECK_541: = CACHE.is_prime;
assert_eq!;
assert_eq!;
// Prime counting
const PRIMES_LEQ_100: = CACHE.prime_pi;
assert_eq!;
// Prime factorization:
assert_eq!
// and more!
// If questions are asked about numbers
// outside the cache it returns None
assert!;
assert!;
Example: primality checking
Use is_prime
to test whether a given number is prime:
use is_prime;
const CHECK: bool = is_prime;
assert!;
Example: generate the three primes after 5000000031
The crate also provides prime generation and sieving functionality for computing
arrays of large prime numbers above or below some limit, without having to also
include every single prime number from 2 and up in the resulting constant,
and thus potentially the binary.
This functionality is most conveniently accessed through the macros primes_segment!
and sieve_segment!
that automatically compute the size of the prime sieve that
is needed for a certain computation.
Compute 3 primes greater than or equal to 5000000031:
use ;
const N: usize = 3;
const PRIMES_GEQ: = primes_segment!;
assert_eq!;
Example: find the next or previous prime numbers
Find the next or previous prime numbers with next_prime
and previous_prime
if they exist and can be represented in a u64
:
use ;
const NEXT: = next_prime;
const PREV: = previous_prime;
const NO_SUCH: = previous_prime;
const TOO_BIG: = next_prime;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
and more!
Features
serde
: derives the Serialize
and Deserialize
traits from serde
for the Primes
struct, as well as a few others.
Uses the serde_arrays
crate to do this, and that crate uses the standard library.
zerocopy
: derives the IntoBytes
trait from zerocopy
for the Primes
struct.
rkyv
: derives the Serialize
, Deserialize
, and Archive
traits from
rkyv
for the Primes
struct.
fast_test
: speeds up primality testing significantly by using the
machine-prime
crate.