simon-andrews / rust-modinverse

Small library for finding modular multiplicative inverses.
https://crates.io/crates/modinverse
The Unlicense
9 stars 4 forks source link

Change from Copy to Clone; extract mod_floor; use .is_* instead of ==; run rustfmt #3

Open sollyucko opened 4 years ago

sollyucko commented 4 years ago

Let me know if you want me to separate out any of these changes. The change from Copy to Clone is the main goal, since it allows using types like BigInt and BigUint.

sollyucko commented 4 years ago

It might also be possible to use references instead of clone, similarly to this:

trait HasModInv {
    fn modinv(&self, m: &Self) -> Option<Self> where Self : Sized;
}

impl<T : Integer + Clone> HasModInv for T where for<'a> &'a T : Add<Output = T> + Rem<Output = T> {
    fn modinv(&self, m: &T) -> Option<T> {
        //modinverse(self, m)
        let ExtendedGcd { gcd, x, .. } = self.extended_gcd(m);
        if !gcd.is_one() {
            None
        } else {
            Some(&(&(&x % m) + m) % m) // Deal with negative values properly
        }
    }
}