const-primes
A crate for generating and working with prime numbers in const contexts.
This lets you for example pre-compute prime numbers at compile time and store them in the binary,
or check whether a number is prime in a const function.
#![no_std]
compatible, and currently supports Rust versions 1.67.1 and newer.
Example: generate primes at compile time
Generate arrays of prime numbers at compile time with the function primes
which uses a segmented sieve of Eratosthenes:
use primes;
const PRIMES: = primes;
assert_eq!;
assert_eq!;
Example: use a cache of generated primes for related computations
The struct Primes
is a wrapper around an array of primes:
use Primes;
const PRIMES: = new;
assert_eq!;
assert_eq!;
and it can be used as a cache of primes for related computations:
const CACHE: = new;
// For primality testing
const CHECK_42: = CACHE.is_prime;
const CHECK_541: = CACHE.is_prime;
assert_eq!;
assert_eq!;
// Or for prime counting
const PRIMES_LEQ_100: = CACHE.count_primes_leq;
assert_eq!;
// Or for prime factorization:
assert_eq!
// 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: sieving
Sieve a range of numbers for their prime status with sieve
:
use sieve;
const PRIME_STATUS: = sieve;
// 0 1 2 3 4 5 6 7 8 9
assert_eq!;
Example: generate the three primes after 5000000031
The crate also provides prime generation and sieving functions that can be used to work with ranges that don't start at zero, e.g. primes_geq
and sieve_lt
. These functions can use large sieves to compute large primes, but don't need to return the entire sieve, just the requested numbers.
They are most conveniently used through the macros primes_segment!
and sieve_segment!
that automatically compute the size of the sieve that's 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: determine the prime status of the three largest numbers less than 100005
use ;
const N: usize = 3;
const PRIME_STATUS_LT: = sieve_segment!
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
std
: implements the Error
trait from the standard library for the error types.
License
Licensed under either of
at your option.
Contribution
Contributions are welcome!
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.