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