const_primes::cache

Struct Primes

Source
pub struct Primes<const N: usize>(/* private fields */);
Expand description

A wrapper around an array that consists of the first N primes. Can use those primes for related computations. Ensures that N is non-zero at compile time.

§Examples

Basic usage:

const PRIMES: Primes<3> = Primes::new();
assert_eq!(PRIMES[2], 5);
assert_eq!(PRIMES.as_array(), &[2, 3, 5]);

Reuse sieved primes for other computations:

const CACHE: Primes<100> = Primes::new();
const PRIME_CHECK: Option<bool> = CACHE.is_prime(541);
const PRIME_COUNT: Option<usize> = CACHE.prime_pi(200);

assert_eq!(PRIME_CHECK, Some(true));
assert_eq!(PRIME_COUNT, Some(46));

// If questions are asked about numbers outside the cache it returns None
assert_eq!(CACHE.is_prime(1000), None);
assert_eq!(CACHE.prime_pi(1000), None);

Implementations§

Source§

impl<const N: usize> Primes<N>

Source

pub const fn new() -> Self

Generates a new instance that contains the first N primes.

Uses a segmented sieve of Eratosthenes.

§Examples

Basic usage:

const PRIMES: Primes<3> = Primes::new();
assert_eq!(PRIMES.as_array(), &[2, 3, 5]);

Determine N through type inference

assert_eq!(Primes::new().as_array(), &[2, 3, 5, 7, 11]);

Specify N manually

let primes = Primes::<5>::new();
assert_eq!(primes.as_array(), &[2, 3, 5, 7, 11]);
§Errors

It is a compile error to use an N of 0.

const NO_PRIMES: Primes<0> = Primes::new();
Source

pub const fn is_prime(&self, n: u32) -> Option<bool>

Returns whether n is prime, if it is smaller than or equal to the largest prime in self.

Uses a binary search.

§Example

Basic usage:

const PRIMES: Primes<100> = Primes::new();
const TMOLTUAE: Option<bool> = PRIMES.is_prime(42);

assert_eq!(PRIMES.is_prime(13), Some(true));
assert_eq!(TMOLTUAE, Some(false));
// 1000 is larger than 541, the largest prime in the cache,
// so we don't know whether it's prime.
assert_eq!(PRIMES.is_prime(1000), None);
Source

pub const fn prime_pi(&self, n: u32) -> Option<usize>

Returns the number of primes smaller than or equal to n, if it’s smaller than or equal to the largest prime in self.

Uses a binary search to count the primes.

§Example

Basic usage:

const CACHE: Primes<100> = Primes::new();
const COUNT1: Option<usize> = CACHE.prime_pi(500);
const COUNT2: Option<usize> = CACHE.prime_pi(11);
const OUT_OF_BOUNDS: Option<usize> = CACHE.prime_pi(1_000);

assert_eq!(COUNT1, Some(95));
assert_eq!(COUNT2, Some(5));
assert_eq!(OUT_OF_BOUNDS, None);
Source

pub fn prime_factorization(&self, number: u32) -> PrimeFactorization<'_>

Returns an iterator over the prime factors of the given number in increasing order as well as their multiplicities.

If a number contains prime factors larger than the largest prime in self, they will not be yielded by the iterator, but their product can be retrieved by calling remainder on the iterator.

If you do not need to know the multiplicity of each prime factor, it may be faster to use prime_factors.

§Examples

Basic usage:

// Contains the primes [2, 3, 5]
const CACHE: Primes<3> = Primes::new();

assert_eq!(CACHE.prime_factorization(15).collect::<Vec<_>>(), &[(3, 1), (5, 1)]);

The second element of the returned tuples is the multiplicity of the prime in the number:

// 1024 = 2^10
assert_eq!(CACHE.prime_factorization(1024).next(), Some((2, 10)));

294 has 7 as a prime factor, but 7 is not in the cache:

// 294 = 2*3*7*7
let mut factorization_of_294 = CACHE.prime_factorization(294);

// only 2 and 3 are in the cache:
assert_eq!(factorization_of_294.by_ref().collect::<Vec<_>>(), &[(2, 1), (3, 1)]);

// the factor of 7*7 can be found with the remainder function:
assert_eq!(factorization_of_294.remainder(), Some(49));
Source

pub fn prime_factors(&self, number: u32) -> PrimeFactors<'_>

Returns an iterator over all the prime factors of the given number in increasing order.

If a number contains prime factors larger than the largest prime in self, they will not be yielded by the iterator, but their product can be retrieved by calling remainder on the iterator.

If you also wish to know the multiplicity of each prime factor of the number, take a look at prime_factorization.

§Examples
// Contains [2, 3, 5]
const CACHE: Primes<3> = Primes::new();

assert_eq!(CACHE.prime_factors(3*5).collect::<Vec<_>>(), &[3, 5]);
assert_eq!(CACHE.prime_factors(2*2*2*2*3).collect::<Vec<_>>(), &[2, 3]);

294 has 7 as a prime factor, but 7 is not in the cache:

// 294 = 2*3*7*7
let mut factors_of_294 = CACHE.prime_factors(294);

// only 2 and 3 are in the cache
assert_eq!(factors_of_294.by_ref().collect::<Vec<_>>(), &[2, 3]);

// the factor of 7*7 can be found with the remainder function
assert_eq!(factors_of_294.remainder(), Some(49));
Source

pub const fn previous_prime(&self, n: u32) -> Option<u32>

Returns the largest prime less than n.
If n is 0, 1, 2, or larger than the largest prime in self this returns None.

Uses a binary search.

§Example
const CACHE: Primes<100> = Primes::new();
const PREV400: Option<u32> = CACHE.previous_prime(400);
assert_eq!(PREV400, Some(397));
Source

pub const fn next_prime(&self, n: u32) -> Option<u32>

Returns the smallest prime greater than n.
If n is larger than or equal to the largest prime in self this returns None.

Uses a binary search.

§Example
const CACHE: Primes<100> = Primes::new();
const NEXT: Option<u32> = CACHE.next_prime(400);
assert_eq!(NEXT, Some(401));

Searches the underlying array of primes for the target integer.

If the target is found it returns a Result::Ok that contains the index of the matching element. If the target is not found in the array a Result::Err is returned that indicates where the target could be inserted into the array while maintaining the sorted order.

§Example

Basic usage:

// [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
const PRIMES: Primes<10> = Primes::new();

const WHERE_29: Result<usize, usize> = PRIMES.binary_search(29);
const WHERE_6: Result<usize, usize> = PRIMES.binary_search(6);
const WHERE_1000: Result<usize, usize> = PRIMES.binary_search(1_000);

assert_eq!(WHERE_29, Ok(9));
assert_eq!(WHERE_6, Err(3));
assert_eq!(WHERE_1000, Err(10));
Source

pub const fn into_array(self) -> [u32; N]

Converts self into an array of size N.

§Example

Basic usage:

const PRIMES: [u32; 5] = Primes::new().into_array();
assert_eq!(PRIMES, [2, 3, 5, 7, 11]);
Source

pub const fn as_array(&self) -> &[u32; N]

Returns a reference to the underlying array.

Source

pub const fn as_slice(&self) -> &[u32]

Returns a slice that contains the entire underlying array.

Source

pub fn iter(&self) -> PrimesIter<'_>

Returns a borrowing iterator over the primes.

§Example

Basic usage:

const PRIMES: Primes<10> = Primes::new();

let mut primes = PRIMES.iter();

assert_eq!(primes.nth(5), Some(&13));
assert_eq!(primes.next(), Some(&17));
assert_eq!(primes.as_slice(), &[19, 23, 29]);
Source

pub const fn get(&self, index: usize) -> Option<&u32>

Returns a reference to the element at the given index if it is within bounds.

§Example

Basic usage:

const PRIMES: Primes<5> = Primes::new();
const THIRD_PRIME: Option<&u32> = PRIMES.get(2);
assert_eq!(THIRD_PRIME, Some(&5));
Source

pub const fn last(&self) -> &u32

Returns a reference to the last prime in self. This is also the largest prime in self.

§Example

Basic usage:

const PRIMES: Primes<5> = Primes::new();
assert_eq!(PRIMES.last(), &11);
Source

pub const fn len(&self) -> usize

Returns the number of primes in self.

§Example

Basic usage:

const PRIMES: Primes<5> = Primes::new();
assert_eq!(PRIMES.len(), 5);
Source

pub const fn totient(&self, n: u32) -> Result<u32, PartialTotient>

Returns the value of the Euler totient function of n: the number of positive integers up to n that are relatively prime to it.

§Example
const CACHE: Primes<3> = Primes::new();
const TOTIENT_OF_6: Result<u32, PartialTotient> = CACHE.totient(2*3);

assert_eq!(TOTIENT_OF_6, Ok(2));
§Errors

The totient function is computed here as the product over all factors of the form p^(k-1)*(p-1) where p is the primes in the prime factorization of n and k is their multiplicity. If n contains prime factors that are not part of self, a Result::Err is returned that contains a PartialTotient struct that contains the result from using only the primes in self, as well as the product of the prime factors that are not included in self.

§Error example

The number 2450 is equal to 2*5*5*7*7. If the cache does not contain 7 the function runs out of primes after 5, and can not finish the computation:

// Contains the primes [2, 3, 5]
const CACHE: Primes<3> = Primes::new();
const TOTIENT_OF_2450: Result<u32, PartialTotient> = CACHE.totient(2*5*5*7*7);

assert_eq!(
    TOTIENT_OF_2450,
    Err( PartialTotient {
//                 totient(2*5*5) = 20
        totient_using_known_primes: 20,
        product_of_unknown_prime_factors: 49
    })
);

Trait Implementations§

Source§

impl<const N: usize> Archive for Primes<N>
where [u32; N]: Archive,

Source§

type Archived = ArchivedPrimes<N>

The archived representation of this type. Read more
Source§

type Resolver = PrimesResolver<N>

The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.
Source§

fn resolve(&self, resolver: Self::Resolver, out: Place<Self::Archived>)

Creates the archived version of this value at the given position and writes it to the given output. Read more
Source§

const COPY_OPTIMIZATION: CopyOptimization<Self> = _

An optimization flag that allows the bytes of this type to be copied directly to a writer instead of calling serialize. Read more
Source§

impl<const N: usize> AsRef<[u32]> for Primes<N>

Source§

fn as_ref(&self) -> &[u32]

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<const N: usize> AsRef<[u32; N]> for Primes<N>

Source§

fn as_ref(&self) -> &[u32; N]

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<const N: usize> Clone for Primes<N>

Source§

fn clone(&self) -> Primes<N>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<const N: usize> Debug for Primes<N>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<const N: usize> Default for Primes<N>

Source§

fn default() -> Self

It is a compile error if N is 0.

Source§

impl<'de, const N: usize> Deserialize<'de> for Primes<N>

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<__D: Fallible + ?Sized, const N: usize> Deserialize<Primes<N>, __D> for Archived<Primes<N>>
where [u32; N]: Archive, <[u32; N] as Archive>::Archived: Deserialize<[u32; N], __D>,

Source§

fn deserialize( &self, deserializer: &mut __D, ) -> Result<Primes<N>, <__D as Fallible>::Error>

Deserializes using the given deserializer
Source§

impl<const N: usize> From<Primes<N>> for [u32; N]

Source§

fn from(const_primes: Primes<N>) -> Self

Converts to this type from the input type.
Source§

impl<const N: usize> Hash for Primes<N>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<const N: usize, I> Index<I> for Primes<N>
where I: SliceIndex<[u32]>,

Source§

type Output = <I as SliceIndex<[u32]>>::Output

The returned type after indexing.
Source§

fn index(&self, index: I) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<const N: usize> IntoBytes for Primes<N>
where [u32; N]: IntoBytes,

Source§

fn as_bytes(&self) -> &[u8]
where Self: Immutable,

Gets the bytes of this value. Read more
Source§

fn write_to(&self, dst: &mut [u8]) -> Result<(), SizeError<&Self, &mut [u8]>>
where Self: Immutable,

Writes a copy of self to dst. Read more
Source§

fn write_to_prefix( &self, dst: &mut [u8], ) -> Result<(), SizeError<&Self, &mut [u8]>>
where Self: Immutable,

Writes a copy of self to the prefix of dst. Read more
Source§

fn write_to_suffix( &self, dst: &mut [u8], ) -> Result<(), SizeError<&Self, &mut [u8]>>
where Self: Immutable,

Writes a copy of self to the suffix of dst. Read more
Source§

impl<'a, const N: usize> IntoIterator for &'a Primes<N>

Source§

type IntoIter = PrimesIter<'a>

Which kind of iterator are we turning this into?
Source§

type Item = &'a u32

The type of the elements being iterated over.
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<const N: usize> IntoIterator for Primes<N>

Source§

type Item = u32

The type of the elements being iterated over.
Source§

type IntoIter = PrimesIntoIter<N>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<const N: usize> KnownLayout for Primes<N>
where Self: Sized,

Source§

type PointerMetadata = ()

The type of metadata stored in a pointer to Self. Read more
Source§

impl<const N: usize> Ord for Primes<N>

Source§

fn cmp(&self, other: &Primes<N>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<const N: usize> PartialEq for Primes<N>

Source§

fn eq(&self, other: &Primes<N>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<const N: usize> PartialOrd for Primes<N>

Source§

fn partial_cmp(&self, other: &Primes<N>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<__S: Fallible + ?Sized, const N: usize> Serialize<__S> for Primes<N>
where [u32; N]: Serialize<__S>,

Source§

fn serialize( &self, serializer: &mut __S, ) -> Result<<Self as Archive>::Resolver, <__S as Fallible>::Error>

Writes the dependencies for the object and returns a resolver that can create the archived type.
Source§

impl<const N: usize> Serialize for Primes<N>

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<const N: usize> Copy for Primes<N>

Source§

impl<const N: usize> Eq for Primes<N>

Source§

impl<const N: usize> Immutable for Primes<N>
where [u32; N]: Immutable,

Source§

impl<const N: usize> StructuralPartialEq for Primes<N>

Auto Trait Implementations§

§

impl<const N: usize> Freeze for Primes<N>

§

impl<const N: usize> RefUnwindSafe for Primes<N>

§

impl<const N: usize> Send for Primes<N>

§

impl<const N: usize> Sync for Primes<N>

§

impl<const N: usize> Unpin for Primes<N>

§

impl<const N: usize> UnwindSafe for Primes<N>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<T> ArchiveUnsized for T
where T: Archive,

Source§

type Archived = <T as Archive>::Archived

The archived counterpart of this type. Unlike Archive, it may be unsized. Read more
Source§

fn archived_metadata( &self, ) -> <<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata

Creates the archived version of the metadata for this value.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

impl<T, S> SerializeUnsized<S> for T
where T: Serialize<S>, S: Fallible + Writer + ?Sized,

Source§

fn serialize_unsized( &self, serializer: &mut S, ) -> Result<usize, <S as Fallible>::Error>

Writes the object and returns the position of the archived type.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,