Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Mod of Negative Numbers (http://www.go4expert.com/forums/mod-negative-t24767/)

 Venny 28Jan2011 07:34

Mod of Negative Numbers

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

 xpi0t0s 28Jan2011 14:50

Re: Mod of Negative Numbers

Quote:
 Originally Posted by Venny (Post 78417) 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.

 All times are GMT +5.5. The time now is 10:26.