Mathematical modulus in c#

馋奶兔 提交于 2019-12-03 05:40:39

问题


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


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



回答2:


x < 0 ? ((x % m) + m) % m : x % m;



回答3:


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 ....



回答4:


a < 0 ? ((a+1)%b + b-1) : (a%b);

That requires only one % operation (and one ternary op) and no multiplication




回答5:


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.




回答6:


Fix :

(ans=a%b)<0 ? (a<0 && b<0 ? (ans-b)%(-b) : (ans+b)%b) : ans




回答7:


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



回答8:


Might be the % operator?

http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx



来源:https://stackoverflow.com/questions/2691025/mathematical-modulus-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!