% (mod) explanation

Wolfy picture Wolfy · Apr 8, 2012 · Viewed 68.8k times · Source

Today I was writing a program in C#, and I used % to calculate some index... My program didn't work, so I debugged it and I realized that "%" is not working like in other program languages that I know.

For example:

In Python % returns values like this:

for x in xrange (-5, 6):
     print x, "% 5 =", x % 5

-5 % 5 = 0
-4 % 5 = 1
-3 % 5 = 2
-2 % 5 = 3
-1 % 5 = 4
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0

In C#:

for (int i = -5; i < 6; i++)
{
    Console.WriteLine(i + " % 5 = " + i % 5);
}

-5 % 5 = 0
-4 % 5 = -4
-3 % 5 = -3
-2 % 5 = -2
-1 % 5 = -1
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0

Did I do something wrong or is % not working like it should?

Answer

David Heffernan picture David Heffernan · Apr 8, 2012

As explained in the comments, the different behaviour is by design. The different languages just ascribe different meanings to the % operator.

You ask:

How can I use modulus operator in C#?

You can define a modulus operator yourself that behaves the same way as the Python % operator:

int mod(int a, int n)
{
    int result = a % n;
    if ((result<0 && n>0) || (result>0 && n<0)) {
        result += n;
    }
    return result;
}