I don't think there isn't any need to check if the number is negative.
A simple function to find the positive modulo would be this -
Edit: Assuming N > 0
and N + N - 1 <= INT_MAX
int modulo(int x,int N){
return (x % N + N) %N;
}
This will work for both positive and negative values of x.
Original P.S: also as pointed out by @chux, If your x and N may reach something like INT_MAX-1 and INT_MAX respectively, just replace int
with long long int
.
And If they are crossing limits of long long as well (i.e. near LLONG_MAX), then you shall handle positive and negative cases separately as described in other answers here.