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
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
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;
}
Well the definition (if I'm not mistaken) is something like this
a mod b = a - b * floor(a/b)
It's probably pretty slow and beware of integer division just like built in modulus :)
Other option is to modify the result of built-in modulus according to the signs of operands. Something like this:
if(a < 0 && b > 0)
{
return (a % b + b) % b;
}
else if ....
Fix :
(ans=a%b)<0 ? (a<0 && b<0 ? (ans-b)%(-b) : (ans+b)%b) : ans
If you're using any of these algorithms and you need to do division also, don't forget to make sure that you subtract 1 when appropriate.
I.e.,
if -5 % 2 = -1
and -5 / 2 = -2
, and if you care that -5 / 2 * 2 + -5 % 2 = -5
, then when you calculate -5 % 2 = 1
, that you also calculate -5 / 2 = -3
.