Search code examples
c#modulo

Mathematical modulus in c#


Is there a library function in c# for the mathematical modulus of a number - by this I specifically mean that a negative integer modulo a positive integer should yield a positive result.

edited to provide an example:

-5 modulo 3 should return 1


Solution

  • Try (a % b) * Math.Sign(a)

    Try this; it works correctly.

    static int MathMod(int a, int b) {
        return (Math.Abs(a * b) + a) % b;
    }