I did some research on GCC's % operator and it seems it doesn't calculate the correct value if it has a negative dividend. Well, I know all the relevant rules of GCC.
Anyway, -3%5 is
- -3 by GCC and
- 2 by Math
I'm using this macro now to correct this behaviour:
#define mod(M, N) (M>=0 ? M%N : (N-abs(M%N))%N)
#define mod2(M, N) (M%N>=0 ? M%N : M%N + N)
They both produces the right value, but look ugly and ineffective. Could you recommend any better (faster) way to do this calculation?
Thanks.