Modulo Operations in Programming With Negative Results
In programming, the modulo operation gives the remainder or signed remainder of a division, after one integer is divided by another integer. It is one of the most used operators in programming. This article discusses when and why the modulo operation yields a negative result.
In C, 3 % 2 returns 1. However, -3 % 2 is -1 and 3 % -2 gives 1.
In Python, -3 % 2 is 1 and 3 % -2 is -1.
Hence, it’s evident that the same expression of -3 % 2 gives different results in different programming languages. This result is more related to mathematics rather than programming. The mathematics mentioned here will help in understanding the questions a little more easily. To understand why this happens, a little knowledge about Euclidean Division and a few points related to Modular Arithmetic is needed.
Euclidean Division: In arithmetic, Euclidean division or division with the remainder is the process of dividing one integer (the dividend) by another (the divisor), in such a way that it produces a quotient and a remainder smaller than the divisor.
Given two integers a and b ( where b ≠ 0 ), there exists unique integers q and r such that: