Mathematical modulus in c#

penguat picture penguat · Apr 22, 2010 · Viewed 23.2k times · Source

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

Answer

SLaks picture SLaks · Apr 22, 2010

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;
}