How can I calculate divide and modulo for integers in C#?
Solution 1
Here's an answer from the MSDN documentation.
When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To determine the remainder of 7 / 3, use the remainder operator (%).
int a = 5;
int b = 3;
int div = a / b; //quotient is 1
int mod = a % b; //remainder is 2
Solution 2
There is also Math.DivRem
quotient = Math.DivRem(dividend, divisor, out remainder);
Solution 3
Fun fact!
The 'modulus' operation is defined as:
a % n ==> a - (a/n) * n
So you could roll your own, although it will be FAR slower than the built in % operator:
public static int Mod(int a, int n)
{
return a - (int)((double)a / n) * n;
}
Edit: wow, misspoke rather badly here originally, thanks @joren for catching me
Now here I'm relying on the fact that division + cast-to-int in C# is equivalent to Math.Floor
(i.e., it drops the fraction), but a "true" implementation would instead be something like:
public static int Mod(int a, int n)
{
return a - (int)Math.Floor((double)a / n) * n;
}
In fact, you can see the differences between % and "true modulus" with the following:
var modTest =
from a in Enumerable.Range(-3, 6)
from b in Enumerable.Range(-3, 6)
where b != 0
let op = (a % b)
let mod = Mod(a,b)
let areSame = op == mod
select new
{
A = a,
B = b,
Operator = op,
Mod = mod,
Same = areSame
};
Console.WriteLine("A B A%B Mod(A,B) Equal?");
Console.WriteLine("-----------------------------------");
foreach (var result in modTest)
{
Console.WriteLine(
"{0,-3} | {1,-3} | {2,-5} | {3,-10} | {4,-6}",
result.A,
result.B,
result.Operator,
result.Mod,
result.Same);
}
Results:
A B A%B Mod(A,B) Equal?
-----------------------------------
-3 | -3 | 0 | 0 | True
-3 | -2 | -1 | -1 | True
-3 | -1 | 0 | 0 | True
-3 | 1 | 0 | 0 | True
-3 | 2 | -1 | 1 | False
-2 | -3 | -2 | -2 | True
-2 | -2 | 0 | 0 | True
-2 | -1 | 0 | 0 | True
-2 | 1 | 0 | 0 | True
-2 | 2 | 0 | 0 | True
-1 | -3 | -1 | -1 | True
-1 | -2 | -1 | -1 | True
-1 | -1 | 0 | 0 | True
-1 | 1 | 0 | 0 | True
-1 | 2 | -1 | 1 | False
0 | -3 | 0 | 0 | True
0 | -2 | 0 | 0 | True
0 | -1 | 0 | 0 | True
0 | 1 | 0 | 0 | True
0 | 2 | 0 | 0 | True
1 | -3 | 1 | -2 | False
1 | -2 | 1 | -1 | False
1 | -1 | 0 | 0 | True
1 | 1 | 0 | 0 | True
1 | 2 | 1 | 1 | True
2 | -3 | 2 | -1 | False
2 | -2 | 0 | 0 | True
2 | -1 | 0 | 0 | True
2 | 1 | 0 | 0 | True
2 | 2 | 0 | 0 | True
Solution 4
Division is performed using the /
operator:
result = a / b;
Modulo division is done using the %
operator:
result = a % b;
kartal
Updated on May 05, 2021Comments
-
kartal almost 3 years
How can I calculate division and modulo for integer numbers in C#?
-
Admin about 13 years+1: Conveniently leaving out the type makes it a better answer :-) I believe this works with System.Numeric.BigInteger in 4.0 too.
-
Cor_Blimey over 11 years% returns the remainder, not the modulus (as you point out). They arent the same thing, and can cause problems when dealing with unusual cases (e.g. negative indexes). However, it can be used like the modulus operator when just looking for, e.g., every 10th iteration of a weakly positive indexer. Perhaps you could explain how to calculate the real modulus?
-
Joren about 11 years"Now here I'm relying on the fact that integer division in C# is equivalent to Math.Floor (i.e., it drops the fraction)" - But it's not. Integer divison rounds towards zero, Math.Floor rounds towards negative infinity.
-
JerKimball about 11 years@Joren Sorry, but no - try running this:
Enumerable.Range(0, 10).Select(x => (double)x / 10.0).Select(x => (int)x).ToList().ForEach(x => Console.WriteLine(x));
- all 0's -
Joren about 11 yearsFirst, I'm talking about integer division. What happens if you do a floating-point division and then cast to integer is irrelevant (even though it gives the same result). Second, I'm not sure why you would expect integers between 0 and 9 to give anything other than 0 after dividing by 10 and truncating to the integer part. If that resulted in 1 that would be rounding away from zero or towards positive infinity. Third, there is no difference whatsoever between rounding towards zero and rounding towards negative infinity for positive numbers, so you're not even addressing the issue.
-
Joren about 11 years
Math.Floor(-10.0 / 3.0)
and-10 / 3
are not the same thing. -
JerKimball about 11 years@joren ah, I see the disconnect here - no, I'm not performing integer division, I'm performing double division, then casting the result to integer - very different.
-
JerKimball about 11 years@joren but you are correct that there is a huge typo in my example. I'll edit it.
-
JerKimball about 11 years@Joren There - sorry about that, you were absolutely correct in catching that; don't know what the heck I was thinking when I wrote up the post...
-
apocalypse about 11 years% --> as Cor_Blimey said, it returns remainder not the modulus. For example: (-5 % 3) == -2 [C#], -5 mod 3 = 1 [wolframalpha.com].
-
apocalypse about 11 yearsTrue, I read posts like this, and I had problems in my application :)
-
leviathanbadger almost 11 years...What exactly is the point of declaring
a
andb
if you aren't going to use them? :D -
Sir Crispalot over 10 years@aboveyou00: fixed that for you!
-
supercat about 10 years@Cor_Blimey: The simplest, safest, and most readable way to calculate the modulus is probably to calculate the remainder and--if it's negative, add the base. If the code is ported to a platform which includes a real modulus operator, the adjust-if-negative code may be redundant, but harmless. If one needs both the quotient and real modulus, the safe approach would be to use
/
for the division, multiply and subtract to yield the remainder of whatever form, and if it's necessary to adjust the remainder, adjust the quotient as well. That will work regardless of what the language does for "/". -
Cor_Blimey about 10 years@supercat thanks for the response. I wasn't sure if there was a bit of syntactic sugar for it instead. And I agree, if in doubt then calculate it 'properly' from first principles to be sure. Thanks.
-
Igor over 8 yearsThis should be the correct answer in my opinion, because it provides the quotient AND the remainder in one function. I am not sure which approach performs better (using "a / b" to get quotient and then "a % b" to get the remainder or Math.DivRem), but this approach certainly is much nicer to read (in my case I need to know both quotient and remainder) - thank you!
-
danodonovan over 8 years@Igor thanks, when the original question was answered this function didn't exist! However, the function's existence does make as-cii's remark about checking the documentation look a bit silly.... :)
-
NightElfik over 8 yearsJust to avoid confusion,
Math.DivRem
does not compute div and mod in one operation. It is just a helper function and its source code is exactly:public static int DivRem(int a, int b, out int result) { result = a%b; return a/b; }
. -
kbolino about 8 years@NightElfik The implementation could change in the future, and it is easier for the runtime to identify a method call for optimization than disjoint
div
andrem
instructions -
Ryan almost 8 yearsNote: Modulo is not the same as Modulus. Modulo is the remainder, Modulus is the absolute value.
-
BenKoshy over 7 years@supercat how can the remainder ever be negative?
-
supercat over 7 years@BKSpurgeon: -1 mod 16 is 15, but -1 divided by 15 is zero remainder -1.
-
Bob about 7 years@kbolino That's a great prediction, since it has changed, at least in .NET Core, to divide & subtract. And there's further optimisations planned in RyuJIT to use a single x86 div instruction, though admittedly the JIT changes should also detect the
%
and/
operators if used individually. -
Tancredi over 5 yearsPerhaps the user was searching (like me) for a DivRem function, so the question could be not as trivial as it seems at first glance. Thanks @danodonovan
-
SansWit almost 5 yearsThe answer is not as simple as this answer claims, as others have also pointed out, and can lead to hard-to-debug mistakes. See https://stackoverflow.com/questions/10065080/mod-explanation