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












34















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!










share|improve this question




















  • 1





    Any reason to use the term modulus instead of modulo (which is more common AFAICS).

    – ideasman42
    Jan 2 '17 at 8:33











  • They might have studied somewhere where the term modulus is used, not knowing that different institutions tend to differ in vocabulary.

    – OliverUv
    Dec 24 '17 at 19:32
















34















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!










share|improve this question




















  • 1





    Any reason to use the term modulus instead of modulo (which is more common AFAICS).

    – ideasman42
    Jan 2 '17 at 8:33











  • They might have studied somewhere where the term modulus is used, not knowing that different institutions tend to differ in vocabulary.

    – OliverUv
    Dec 24 '17 at 19:32














34












34








34


2






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!










share|improve this question
















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!







rust modulo






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 2:37









Shepmaster

156k14315457




156k14315457










asked Jul 3 '15 at 15:39









KapichuKapichu

1,02421027




1,02421027








  • 1





    Any reason to use the term modulus instead of modulo (which is more common AFAICS).

    – ideasman42
    Jan 2 '17 at 8:33











  • They might have studied somewhere where the term modulus is used, not knowing that different institutions tend to differ in vocabulary.

    – OliverUv
    Dec 24 '17 at 19:32














  • 1





    Any reason to use the term modulus instead of modulo (which is more common AFAICS).

    – ideasman42
    Jan 2 '17 at 8:33











  • They might have studied somewhere where the term modulus is used, not knowing that different institutions tend to differ in vocabulary.

    – OliverUv
    Dec 24 '17 at 19:32








1




1





Any reason to use the term modulus instead of modulo (which is more common AFAICS).

– ideasman42
Jan 2 '17 at 8:33





Any reason to use the term modulus instead of modulo (which is more common AFAICS).

– ideasman42
Jan 2 '17 at 8:33













They might have studied somewhere where the term modulus is used, not knowing that different institutions tend to differ in vocabulary.

– OliverUv
Dec 24 '17 at 19:32





They might have studied somewhere where the term modulus is used, not knowing that different institutions tend to differ in vocabulary.

– OliverUv
Dec 24 '17 at 19:32












2 Answers
2






active

oldest

votes


















18















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. .






share|improve this answer





















  • 1





    I, as a C/C++ programmer, am embarrassed that I didn't know that % works in C that way, too...

    – Kapichu
    Jul 3 '15 at 16:08






  • 1





    Isn't this a gap in Rust?

    – Kapichu
    Jul 3 '15 at 16:09






  • 1





    Well, as you expect, this is not something mathematicians enjoy. And i would not say it is a gap, for all this family of languages % is just the remainder.

    – JosEduSol
    Jul 3 '15 at 16:20






  • 1





    I'll go with % being the remainder, but not having support for modulus sucks...

    – Kapichu
    Jul 3 '15 at 16:24











  • @JosEduSol As I write this, the answer above shows (a % b) + b as a way to calculate the modulus, but I'm pretty sure what you meant to write is this: ((a % b) + b) % b.

    – David J.
    Nov 21 '18 at 1:58





















5














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 }





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31210357%2fis-there-a-modulus-not-remainder-function-operation%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    18















    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. .






    share|improve this answer





















    • 1





      I, as a C/C++ programmer, am embarrassed that I didn't know that % works in C that way, too...

      – Kapichu
      Jul 3 '15 at 16:08






    • 1





      Isn't this a gap in Rust?

      – Kapichu
      Jul 3 '15 at 16:09






    • 1





      Well, as you expect, this is not something mathematicians enjoy. And i would not say it is a gap, for all this family of languages % is just the remainder.

      – JosEduSol
      Jul 3 '15 at 16:20






    • 1





      I'll go with % being the remainder, but not having support for modulus sucks...

      – Kapichu
      Jul 3 '15 at 16:24











    • @JosEduSol As I write this, the answer above shows (a % b) + b as a way to calculate the modulus, but I'm pretty sure what you meant to write is this: ((a % b) + b) % b.

      – David J.
      Nov 21 '18 at 1:58


















    18















    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. .






    share|improve this answer





















    • 1





      I, as a C/C++ programmer, am embarrassed that I didn't know that % works in C that way, too...

      – Kapichu
      Jul 3 '15 at 16:08






    • 1





      Isn't this a gap in Rust?

      – Kapichu
      Jul 3 '15 at 16:09






    • 1





      Well, as you expect, this is not something mathematicians enjoy. And i would not say it is a gap, for all this family of languages % is just the remainder.

      – JosEduSol
      Jul 3 '15 at 16:20






    • 1





      I'll go with % being the remainder, but not having support for modulus sucks...

      – Kapichu
      Jul 3 '15 at 16:24











    • @JosEduSol As I write this, the answer above shows (a % b) + b as a way to calculate the modulus, but I'm pretty sure what you meant to write is this: ((a % b) + b) % b.

      – David J.
      Nov 21 '18 at 1:58
















    18












    18








    18








    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. .






    share|improve this answer
















    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. .







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 21 '18 at 20:01









    Shepmaster

    156k14315457




    156k14315457










    answered Jul 3 '15 at 16:01









    JosEduSolJosEduSol

    3,98031629




    3,98031629








    • 1





      I, as a C/C++ programmer, am embarrassed that I didn't know that % works in C that way, too...

      – Kapichu
      Jul 3 '15 at 16:08






    • 1





      Isn't this a gap in Rust?

      – Kapichu
      Jul 3 '15 at 16:09






    • 1





      Well, as you expect, this is not something mathematicians enjoy. And i would not say it is a gap, for all this family of languages % is just the remainder.

      – JosEduSol
      Jul 3 '15 at 16:20






    • 1





      I'll go with % being the remainder, but not having support for modulus sucks...

      – Kapichu
      Jul 3 '15 at 16:24











    • @JosEduSol As I write this, the answer above shows (a % b) + b as a way to calculate the modulus, but I'm pretty sure what you meant to write is this: ((a % b) + b) % b.

      – David J.
      Nov 21 '18 at 1:58
















    • 1





      I, as a C/C++ programmer, am embarrassed that I didn't know that % works in C that way, too...

      – Kapichu
      Jul 3 '15 at 16:08






    • 1





      Isn't this a gap in Rust?

      – Kapichu
      Jul 3 '15 at 16:09






    • 1





      Well, as you expect, this is not something mathematicians enjoy. And i would not say it is a gap, for all this family of languages % is just the remainder.

      – JosEduSol
      Jul 3 '15 at 16:20






    • 1





      I'll go with % being the remainder, but not having support for modulus sucks...

      – Kapichu
      Jul 3 '15 at 16:24











    • @JosEduSol As I write this, the answer above shows (a % b) + b as a way to calculate the modulus, but I'm pretty sure what you meant to write is this: ((a % b) + b) % b.

      – David J.
      Nov 21 '18 at 1:58










    1




    1





    I, as a C/C++ programmer, am embarrassed that I didn't know that % works in C that way, too...

    – Kapichu
    Jul 3 '15 at 16:08





    I, as a C/C++ programmer, am embarrassed that I didn't know that % works in C that way, too...

    – Kapichu
    Jul 3 '15 at 16:08




    1




    1





    Isn't this a gap in Rust?

    – Kapichu
    Jul 3 '15 at 16:09





    Isn't this a gap in Rust?

    – Kapichu
    Jul 3 '15 at 16:09




    1




    1





    Well, as you expect, this is not something mathematicians enjoy. And i would not say it is a gap, for all this family of languages % is just the remainder.

    – JosEduSol
    Jul 3 '15 at 16:20





    Well, as you expect, this is not something mathematicians enjoy. And i would not say it is a gap, for all this family of languages % is just the remainder.

    – JosEduSol
    Jul 3 '15 at 16:20




    1




    1





    I'll go with % being the remainder, but not having support for modulus sucks...

    – Kapichu
    Jul 3 '15 at 16:24





    I'll go with % being the remainder, but not having support for modulus sucks...

    – Kapichu
    Jul 3 '15 at 16:24













    @JosEduSol As I write this, the answer above shows (a % b) + b as a way to calculate the modulus, but I'm pretty sure what you meant to write is this: ((a % b) + b) % b.

    – David J.
    Nov 21 '18 at 1:58







    @JosEduSol As I write this, the answer above shows (a % b) + b as a way to calculate the modulus, but I'm pretty sure what you meant to write is this: ((a % b) + b) % b.

    – David J.
    Nov 21 '18 at 1:58















    5














    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 }





    share|improve this answer






























      5














      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 }





      share|improve this answer




























        5












        5








        5







        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 }





        share|improve this answer















        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 }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 21 '18 at 20:01









        Shepmaster

        156k14315457




        156k14315457










        answered Jan 2 '17 at 6:01









        ideasman42ideasman42

        12.8k569134




        12.8k569134






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31210357%2fis-there-a-modulus-not-remainder-function-operation%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings