c# 中是否有用于数字数学模数的库函数 - 我特意指的是负整数模正整数应该产生正结果。
编辑提供了一个例子:
-5 模 3 应返回 1
尝试
(a % b) * Math.Sign(a)
试试这个;它工作正常。
static int MathMod(int a, int b) {
return (Math.Abs(a * b) + a) % b;
}
x < 0 ? ((x % m) + m) % m : x % m;
好吧,定义(如果我没记错的话)是这样的
a mod b = a - b * 楼层(a/b)
它可能非常慢,并且要小心整数除法,就像内置模数一样:)
另一种选择是根据操作数的符号修改内置模的结果。像这样的东西:
if(a < 0 && b > 0)
{
return (a % b + b) % b;
}
else if ....
a < 0 ? ((a+1)%b + b-1) : (a%b);
只需要一次 % 运算 (
and one ternary op
),无需乘法
如果您使用任何这些算法并且还需要进行除法,请不要忘记确保在适当的时候减去 1。
即,
如果
-5 % 2 = -1
和-5 / 2 = -2
,并且如果您关心-5 / 2 * 2 + -5 % 2 = -5
,那么当您计算-5 % 2 = 1
时,您也会计算-5 / 2 = -3
。
修复:
(ans=a%b)<0 ? (a<0 && b<0 ? (ans-b)%(-b) : (ans+b)%b) : ans
我知道这个问题没有要求它,但我只是编写并测试了一个也返回商的方法。我找的时候没找到,所以我想把它放在那里。
/// <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;
}
有点晚了,但是...模数运算是除法的提醒,这存在于数学中: double module = Math.IEEERemainder(x, y);