Is there a modulus (not remainder) function / oper

2019-02-11 10:14发布

问题:

In Rust (like most programming languages), the % operator performs the remainder operation, not the modulus operation. These operations have different results for negative numbers:

-21 modulus 4 => 3
-21 remainder 4 => -1
println!("{}", -21 % 4); // -1

However, I want the modulus.

I found a workaround ((a % b) + b) % b, but I don't want to reinvent the wheel if there's already a function for that!

回答1:

Is there a modulus (not remainder!) function / operation in Rust?

As far as I can tell, there is no modular arithmetic function.

This also happens in C, where it is common to use the workaround you mentioned: (a % b) + b.

In C, C++, D, C#, F# and Java, % is in fact the remainder. In Perl, Python or Ruby, % is the modulus.

Language developers don't always go the "correct mathematical way", so computer languages might seem weird from the strict mathematician view. The thing is that both modulus and remainder, are correct for different uses.

Modulus is more mathematical if you like, while the remainder (in the C-family) is consistent with common integer division satisfying: (a / b) * b + a % b = a; this is adopted from old Fortran. So % is better called the remainder, and I suppose Rust is being consistent with C.

You are not the first to note this:

  • No modulo operator?
  • Remainder is not modulus, but int::rem() uses the mod operator. .


回答2:

No, Rust doesn't have a built in modulus, see this discussion for some reasons why.

Here's an example that might be handy:

///
/// Modulo that handles negative numbers, works the same as Python's `%`.
///
/// eg: `(a + b).modulo(c)`
///
pub trait ModuloSignedExt {
    fn modulo(&self, n: Self) -> Self;
}
macro_rules! modulo_signed_ext_impl {
    ($($t:ty)*) => ($(
        impl ModuloSignedExt for $t {
            #[inline]
            fn modulo(&self, n: Self) -> Self {
                (self % n + n) % n
            }
        }
    )*)
}
modulo_signed_ext_impl! { i8 i16 i32 i64 }


标签: rust modulo