When a is negative, different languages handle % differently. In Python, -17 % 5 gives 3. In C++ and Java, -17 % 5 gives -2.
Mathematically, we want remainders between 0 and m - 1. If you get a negative result in C++ or Java, add m to fix it: result = ((a % m) + m) % m.
This formula always gives the correct positive remainder.