Ragib Asif

Software Engineer, Mathematician, Writer, Artist, Poet

← Back to all posts

Compute the Euclidean Modulo in C

The modulus is the remainder of the Euclidean division, which produces an integer quotient and natural number remainder. This is also known as the modulo operation.

The C programming language contains an operator %, known as the remainder operator, which is often mistakenly treated as a modulo operator. Although, the % already behaves like the Euclidean modulo for unsigned numbers, this is not the case for negative numbers.

The canonical way that many C programmers get around this is by using a simple one-liner: ((a % b) + b) % b. As common as this solution is, it’s far from ideal. This method assumes b > 0, doesn’t check for integer overflow, and the extra % b is usually unnecessary.

A much better solution, and I happen to be a bit biased since I use this method, is the following:

int mod( int a, int b ) {
    /* b == 0 is UB/Division by zero error */
    if ( b == 0 ) {
        return 0;
    }
    /* Mathematically this will evaluate to 0 if b is -1 */
    /* It's also UB because of integer overflow */
    if ( a == INT_MIN && b == -1 ) {
        return 0;
    }
    int r = a % b;
    if ( r < 0 ) { r += abs( b ); }
    return r;
}