Vienna

Herwig Teufer

Data Engineer · Bouldering Enthusiast · Hobby Blogger

Wednesday, 2 December 2026Personal editionteufer.dev

Advent of Codecpp

Modulo in cpp behaves "unexpected"

In cpp the modulo operator behaves different than expected coming from Math (or python). When taking a negative number modulo a positive number, the result is always a negative number.

For example in cpp -1 % 3 = -1

and in python -1 % 3 = 2

This is based on how the language defines integer division. cpp rounds towards 0 -> we always have a negative (or 0 if divides evenly) remainder if the dividend (in the example -1) is negative.

What does this have to do with rounding towards 0?

See here:

-7 / 3 == -2 -> -7 - (-2 * 3) = -1 remaining

In python on the other hand we floor towards -∞:

-7 // 3 == -3 -> -7 - (-3 * 3) = 2 remaining

This comes from the equation: r = a − (q * b)