This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Modulo operation in C for -ve values
- From: "Deepak Gaur" <dgaur at cdotd dot ernet dot in>
- To: gcc at gcc dot gnu dot org
- Date: Fri, 16 Nov 2007 09:27:22 +0530
- Subject: Modulo operation in C for -ve values
- References: <1194564963-15626-1-git-send-email-Emilian.Medve@Freescale.com>< 18231.60427.229658.485287@cargo.ozlabs.ibm.com> <200711121901.39163.rusty@rustcorp.com.au> <20071112115350.M72594@cdotd.ernet.in> <20071113050628.M58911@cdotd.ernet.in> <20071113050819.M54902@cdotd.ernet.in>
Subject: Modulo operation in C for -ve values
The Modulo operation as specified in
http://xenia.media.mit.edu/~bdenckla/thesis/texts/htthe/node13.html says that
for a fraction like n/k which can be expressed as n/k = i + j/k the C division
and mod operation should yeild
n div k = i (integer part)
n mod k = j (remainder part)
For n +ve above is true
For n -ve
-n/k = -i + j/k
-n div k = -i
-n mod k = j (+ve remainder)
But running a sample program on Redhat enterprise Linux EL4
with gcc version 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)
on a Intel PIV Machine
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n,k,j;
n=-3;
k=8; /* k is power of 2 */
j=(n/k);
printf("n n div k = %d", j);
j=(n%k);
printf("\n n mod k = %d", j);
j=(n) & (k-1);
printf("\n n & k-1 = %d", j);
}
gives following output for n = -3 k = 8
n div k = 0
n mod k = -3
n & k-1 = 5
though it should have been as per hypothesis proposed in
http://xenia.media.mit.edu/~bdenckla/thesis/texts/htthe/node13.html
n div k = -1
n mod k = 5
n & k-1 = 5
Which is correct(0,-3,5) or (-1,5,5)?
Thanks
Deepak Gaur