In a C program i was trying the below operations(Just to check the behavior )
x = 5 % (-3);
y = (-5) % (3);
z = (-5) % (-3);
printf(\"%d ,%d ,%d\", x, y
I believe it's more useful to think of mod
as it's defined in abstract arithmetic; not as an operation, but as a whole different class of arithmetic, with different elements, and different operators. That means addition in mod 3
is not the same as the "normal" addition; that is; integer addition.
So when you do:
5 % -3
You are trying to map the integer 5 to an element in the set of mod -3
. These are the elements of mod -3
:
{ 0, -2, -1 }
So:
0 => 0, 1 => -2, 2 => -1, 3 => 0, 4 => -2, 5 => -1
Say you have to stay up for some reason 30 hours, how many hours will you have left of that day? 30 mod -24
.
But what C implements is not mod
, it's a remainder. Anyway, the point is that it does make sense to return negatives.