pub trait Mod: Sized + Sealed {
type Native;
const MODULUS: Self::Native;
const ZERO: Self;
const ONE: Self;
// Required methods
fn new(x: Self::Native) -> Self;
unsafe fn new_unchecked(x: Self::Native) -> Self;
fn remainder(self) -> Self::Native;
fn to_raw(self) -> Self::Native;
fn is<const C: u64>(self) -> bool;
fn is_zero(&self) -> bool;
fn pow(self, n: u64) -> Self;
fn is_invertible(&self) -> bool;
fn inverse(self) -> Option<Self>;
}Expand description
A common interface for modular arithmetic.
This trait is implemented by all types in this crate.
Required Associated Constants§
Required Associated Types§
Required Methods§
Sourceunsafe fn new_unchecked(x: Self::Native) -> Self
unsafe fn new_unchecked(x: Self::Native) -> Self
Create a value corresponding to x, assuming x is a correct representation for this type.
This function is most useful for prime moduli, since it’s faster than new for
those types.
§Safety
This function is safe to call if either of the two conditions holds:
xis less than the modulus, orxwas produced byto_rawon the same type.
Sourcefn to_raw(self) -> Self::Native
fn to_raw(self) -> Self::Native
Get the internal optimized representation of the number.
This returns some value equivalent to x modulo m, but not necessarily x mod m itself.
This is more efficient than remainder for prime moduli. Passing this
value to new or new_unchecked
is guaranteed to produce the same value as self.
Sourcefn is<const C: u64>(self) -> bool
fn is<const C: u64>(self) -> bool
Compare for equality with a constant.
For fast moduli, this is more efficient than x == FastK::new(C). C must be a valid
reminder, i.e. C < m.
C is typed u64 instead of Native due to Rust having issues with
associated types in const.
Sourcefn pow(self, n: u64) -> Self
fn pow(self, n: u64) -> Self
Compute x^n mod m.
The current implementation uses iterative binary exponentiation, combining it with the
Carmichael function to reduce exponents. It works in O(log n).
Sourcefn is_invertible(&self) -> bool
fn is_invertible(&self) -> bool
Check if the value is invertible, i.e. if x is coprime with m.
The current implementation checks x % p != 0 for all prime factors p of the modulus.
This is very fast for PowerK, relatively fast for PrimeK/BigPrimeK and slightly slow
for FastK.
Sourcefn inverse(self) -> Option<Self>
fn inverse(self) -> Option<Self>
Compute the multiplicative inverse.
Returns None if x is not coprime with m.
For power-of-two moduli, the current implementation uses an algorithm by
Hurchalla, which works in O(log k). For other moduli, it uses a variation of
Pornin’s algorithm, which works in O(k).
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.