Am Freitag, 16. November 2007 10:31:35 schrieb Andrew Haley: > I've redirected this to gcc-help, since it's a question about using > gcc, not about developing gcc. > > Deepak Gaur writes: > > 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) actually in this problem you can see the sense behind your thesis It is statet there that it seems that -3 ./. 7 = 0 + (-3/7) where i = -((-n) div k) and j = - ((-n) mod k) (n<0) [WRONG!] does not hold but i = -((-n) div k)-1 and j = - ((-n) mod k)+k (n<0) [works] moving the sign carrier to the integer part. This always works since (0<=j<k) ! Now you have your complete algorithm. Happy mathing bye ingo > > > > 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)? > > gcc is correct. Your mistake is to assume that the C operator % > represents the mathematical modulo. It doesn't: % is the remainder > after division, not modulo arithmetic. C only supports modulo on > unsigned quantities. > > Andrew. -- Mit freundlichen Grüßen / kind regards I n g o K r a b b e System Administrator / system administrator _________________________________________________________________________ Elements of Art GmbH http://www.eoa.de An der Eickesmuehle 22 41238 D-Moenchengladbach / Germany fon: +49 (2166) 91567-3418 Registergericht: Moenchengladbach HRB 5855 fax: +49 (2166) 91567-99 Geschaeftsfuehrer: Erik Winterberg, Sebastian Leppert