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;
}
x < 0 ? ((x % m) + m) % m : x % m;
x = 1
and m = int.MaxValue
(or in any scenario where 0 < x < m and x + m > int.MaxValue). –
Governance 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 ....
a < 0 ? ((a+1)%b + b-1) : (a%b);
That requires only one % operation (and one ternary op
) and no multiplication
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
.
Fix :
(ans=a%b)<0 ? (a<0 && b<0 ? (ans-b)%(-b) : (ans+b)%b) : ans
I know the question didn't ask for it, but I just wrote and tested a method which returns the quotient as well. Didn't find this when I was looking for it, so I thought I'd put it out there.
/// <summary>
/// Compute integer quotient and remainder of <paramref name="dividend"/> / <paramref name="divisor"/>
/// where the <paramref name="remainder"/> has the same sign as <paramref name="divisor"/>, and is
/// between zero (inclusive) and the <paramref name="divisor"/> (exclusive). As always,
/// (quotientResult * <paramref name="divisor"/> + <paramref name="remainder"/> == <paramref name="dividend"/>).
/// </summary>
public static int DivRemPeriodic(int dividend, int divisor, out int remainder) {
var quotient = Math.DivRem(dividend, divisor, out remainder);
if (divisor > 0 ? remainder < 0 : remainder > 0) {
remainder += divisor;
quotient -= 1;
}
return quotient;
}
The modulus operation is the reminder of a division and this exists in Math:
double module = Math.IEEERemainder(x, y);
Might be the % operator?
-5 % 2
to be +1, not -1. –
Anhwei © 2022 - 2024 — McMap. All rights reserved.