Euclidean (floored) modulo (mod, %) operator for C, C++

Alec Jacobson

June 24, 2010

weblog/

Once again, I was gotcha-ed by the sign of the mod operator in C++. I did -1%n, hoping to get n-1 but instead got -1. Here's a little C/C++ function (you could even macro/inline it) to give the "true" (Euclidean) modulo:
static int mod(int a, int base){    
  return ((a % base) + base) % base;
}
Update: So the above runs about twice as slow as just issuing % once, which is to be expected since % is called twice (guess + is pretty cheap in comparison). If half the time a will be positive and half the time negative then a average speed up of 1.5x over the above code can be achieved with the following:
static int mod(int a, int base){    
  return (a < 0 ? ((a % base) + base) % base : a % base);
}
But it is still slower if you already know for sure that a is not negative. Update: It's worth noting, as it was noted in the comments, that what I describe above is only correct if the base is positive. If the base is negative than euclidean modulo allows a negative result and must be defined accordingly.