const_primes

Function primes_geq

Source
pub const fn primes_geq<const N: usize, const MEM: usize>(
    lower_limit: u64,
) -> Result<[u64; N], GenerationError>
Expand description

Returns the N smallest primes greater than or equal to lower_limit.

This function uses a segmented sieve of size MEM for computation, but only stores the N requested primes in the output array.

Set MEM such that MEM^2 is larger than the largest prime you will encounter.

If you want to compute primes smaller than some limit, take a look at primes_lt.

If you do not wish to compute the size requirement of the sieve manually, take a look at primes_segment!.

§Examples

Basic usage:

use const_primes::primes_geq;
// Compute 5 primes larger than 40. The largest will be 59, so `MEM` needs to be at least 8.
const PRIMES: [u64; 5] = match primes_geq::<5, 8>(40) {Ok(ps) => ps, Err(_) => panic!()};
assert_eq!(PRIMES, [41, 43, 47, 53, 59]);

Compute limited ranges of large primes. Functions provided by the crate can help you compute the needed sieve size:

use const_primes::isqrt;
const N: usize = 3;
const LIMIT: u64 = 5_000_000_030;
const MEM: usize = isqrt(LIMIT) as usize + 1 + N;
const PRIMES_GEQ: Result<[u64; N], GenerationError> = primes_geq::<N, MEM>(LIMIT);
assert_eq!(PRIMES_GEQ, Ok([5_000_000_039, 5_000_000_059, 5_000_000_063]));

§Errors

Only primes smaller than MEM^2 can be generated, so if the sieve encounters a number larger than that it results in an error:

const PRIMES: Result<[u64; 3], GenerationError> = primes_geq::<3, 3>(5);
// The sieve is unable to determine the prime status of 9,
// since that is the same or larger than `MEM`^2.
assert_eq!(PRIMES, Err(GenerationError::SieveOverrun(9)));

Also returns an error if lower_limit is larger than or equal to MEM^2:

const PRIMES: Result<[u64; 5], GenerationError> = primes_geq::<5, 5>(26);
assert_eq!(PRIMES, Err(GenerationError::TooSmallSieveSize));

It is a compile error if MEM is smaller than N, or if MEM^2 does not fit in a u64:

const TOO_SMALL_MEM: Result<[u64; 5], GenerationError> = primes_geq::<5, 2>(20);
const TOO_BIG_MEM: Result<[u64; 10], GenerationError> = primes_geq::<10, 1_000_000_000_000>(100);