The modulus operator in .NET

Stefan Alfbo - Feb 24 - - Dev Community

Something that I have been able to avoid is how the modulus operator % is implemented in different programming languages.

While trying to implement and learn some cryptographic algorithms in .NET (F# mostly of course) I got into some trouble with the modulus operator.

Here is a clear example:

dotnet fsi
> -10 % 3;;
val it: int = -1

python3
>>> -10 % 3
2
Enter fullscreen mode Exit fullscreen mode

After some research I found this blog post, What's the difference? Remainder vs Modulus by Eric Lippert.

The % operator does not give the canonical modulus, it gives the remainder.

So the thing is that some programming languages are implementing the % operator either as a canonical modulus or as the remainder operation.

In this case I want the canonical one and not the remainder that .NET uses.

To keep going with my cryptographic explorations in F#, I used this implementation which is inspired by this issue, Proposal: New operator %% for canonical Modulus operations, from the C# Language Design repository.

let (%%) a b =
    let c = a % b
    if (c < 0 && b > 0) || (c > 0 && b < 0) then
        c + b
    else
        c
Enter fullscreen mode Exit fullscreen mode

Now I can use it like this.

dotnet fsi
> -10 %% 3;;
val it: int = 2
Enter fullscreen mode Exit fullscreen mode

Happy modulus!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .