128

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!

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Kapichu
  • 3,346
  • 4
  • 19
  • 38

4 Answers4

108

RFC 2196 adds a couple of integer methods related to euclidian division. Specifically, the rem_euclid method (example link for i32) is what you are searching for:

println!("{}", -1i32 % 4);                // -1
println!("{}", (-21i32).rem_euclid(4));   // 3

This method is available in rustc 1.38.0 (released on 2019-09-27) and above.

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
  • 3
    They are also implemented for unsigned variants, although it is not possible to figure out what they do from that documentation. I would also mention `div_euclid()` for completeness. But this should be the selected answer anyway. – nert May 10 '20 at 11:50
  • @nert when you see `int_impl!` you can go to this file and see the actual implementation: https://github.com/rust-lang/rust/blob/81799cd8fd841e23b52876ae5e22faeb3ad04eb5/library/core/src/num/int_macros.rs#L672-L696 – Anemoia Apr 28 '22 at 05:21
  • such a misnomer. remainder should be modulos and modulos remainder. – Nearoo Dec 13 '22 at 14:20
43

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) % 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:

AldaronLau
  • 1,044
  • 11
  • 15
JosEduSol
  • 5,268
  • 3
  • 23
  • 31
10

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 }
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ideasman42
  • 42,413
  • 44
  • 197
  • 320
-2

From the other answers I constructed:

fn n_mod_m <T: std::ops::Rem<Output = T> + std::ops::Add<Output = T> + Copy>
  (n: T, m: T) -> T {
    ((n % m) + m) % m
}

assert_eq!(n_mod_m(-21, 4), 3);
Alexx Roche
  • 3,151
  • 1
  • 33
  • 39
  • 2
    If you're going to use that on integers, how is it better than the built-in [`rem_euclid` mentioned in Lukas Kalbertodt's answer](https://stackoverflow.com/a/57342011/2733851)? – mcarton Aug 26 '20 at 00:37
  • I find this explicit function easier to mentally parse than the opaque .rem_euclid() – Alexx Roche Aug 27 '20 at 14:05