How to make the mod of a negative number to be positive?

Most easily: ((x % 5) + 5) % 5


Add the base if the input number X is negative:

X % Y + (X % Y < 0 ? Y : 0);

The quick & dirty way is to write

((x % divisor) + divisor) % divisor

For example, ((-3 % 5) + 5) % 5 == 2. However this performs two separate divisions, and since divisions are one of the slowest arithmetic operations you might like one of these alternatives:

(1) General mod for integer or floating point

int mod(int x, int divisor)
{
    int m = x % divisor;
    return m + (m < 0 ? divisor : 0);
}

template<class Num> Num mod(Num x, Num divisor)
{
    Num m = x % divisor;
    return m + (m < 0 ? divisor : 0);
}

(2) Non-branching mod for 32-bit integers

int mod(int x, int divisor)
{
    int m = x % divisor;
    return m + ((m >> 31) & divisor);
}

All this assumes that the divisor is always positive.

Tags:

C++