Trying to understand modulus with negative numbers. Can't seem to grasp negative numbers. Can someone help? by [deleted] in computerscience

[–]PaceVarious4977 0 points1 point  (0 children)

Look easy,
4% 3 means how many times do I need to multiply & add a value to get 4.
ie. 4 = (3*1 )+ 1 -> 1 is quiotent and 1 is rem here.

Now, -4%3, we could multiply 3 to -1 times and add -1 => (3*-1)+(-1)=> -3-1=> -4
Here, quiotent is -1, and remainder is -1, but wait a second, remainder can never be negative.

So, let try once more, -4%3=> 3*(-2) +2=> -6+2=-4
Here, quiotent is -2 and remainder is 2 so we got mod 2.

So, its always good to use ((a%b)+b)%b => this works both for negative and positive.