Mod of Negative Numbers

Venny's Avatar, Join Date: Jan 2011
Go4Expert Member
Hi All,

This may not b a new question to most of you but since am a newbie, please consider answering this.

For languages like c/c++ and java, how does mod % operator work with negative numbers.

for e.g and trying to fetch the output of -3%2 . The actual output is -1 whereas it should be just one.

Could you help me to come out with a solution on how shall I generate the correct output for negative numbers.

thanks
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Quote:
Originally Posted by Venny View Post
The actual output is -1 whereas it should be just one.
Looks like it's not as simple as that: http://en.wikipedia.org/wiki/Modulo_operation

Visual C++ 2008 test code:
Code:
void test39()
{
	for (int i=5; i>=-5; i--)
	{
		for (int j=-5; j<=5; j++)
		{
			if (j) printf("%4d",i%j); fflush(stdout);
		}
		printf("\n"); fflush(stdout);
	}
}
Output:
Code:
   0   1   2   1   0   0   1   2   1   0
   4   0   1   0   0   0   0   1   0   4
   3   3   0   1   0   0   1   0   3   3
   2   2   2   0   0   0   0   2   2   2
   1   1   1   1   0   0   1   1   1   1
   0   0   0   0   0   0   0   0   0   0
  -1  -1  -1  -1   0   0  -1  -1  -1  -1
  -2  -2  -2   0   0   0   0  -2  -2  -2
  -3  -3   0  -1   0   0  -1   0  -3  -3
  -4   0  -1   0   0   0   0  -1   0  -4
   0  -1  -2  -1   0   0  -1  -2  -1   0
This seems correct to me. -3 % 2 calculates the remainder after the division -3 / 2. There are -1 2's in -3 so -3 / 2 = -1. After subtracting -1*2 from -3 you're left with -1.

If you think it should be 1, does that mean you think the division should return -2? If you subtract X from -3 to get +1 then X has to be -4, i.e. -2*2.