0
votes

I found this definition for modulo

mod(a, n) = a - n * floor(a / n)

Doing an integer division and then multiplying it again means finding the biggest number smaller than a that is dividable by n without a remainder. Subtracting this from a yields the remainder of the division and by that the modulo." source:https://torstencurdt.com/tech/posts/modulo-of-negative-numbers/

It seemed to help me understand intuitively, and it worked for cases where both a and n where positive and also cases where a was negative while b was positive. For example:

-10 mod 3

-12 is the largest number smaller than -10 divisible by 3. So the remainder is -10-(-12)=2 which is correct.

But when I tried doing 10 mod -3 my answer was incorrect. Because while 9 is the largest number smaller than 10 divisible by -3 it will give the wrong answer as it would evaluate to 10-9=1.

Instead it is supposed to be 10 -((-4)*(-3))=10-12=-2.

But 12 isn't the biggest number smaller than a.

I understand how to solve for the answer using the formula a= (a//n)(n)+(a%n) in python. But is there an intuitive definition to help me understand?

2
(a) You say you found “this definition” for modulo, but you do not say where you found it, so we cannot tell you whether that is a good source or examine it to see the context and definitions it uses. (b) For 10/-3, you say “my answer was incorrect.” But you do not tell us either what your answer was or what your Python implementation gave.Eric Postpischil
@ Eric Postpischil "it will give the wrong answer as it would evaluate to 10-9=1."sniperking

2 Answers

0
votes

I found an anser here https://en.wikipedia.org/wiki/Remainder it seems there are two types of remainders and a programming languages picks which one to use

0
votes

The Python 3 documentation gives the identity x == (x//y)*y + (x%y), from which it can be deduced that x%y == x - (x//y)*y. // denotes “floor division”; x//y is the greatest integer not greater than x/y.

For x=10 and y==−3, x/y is −3⅓. floor(−3⅓) is −4. Therefore x//y is −4. Then x - (x//y)*y is 10 − (−4)*−3 = 10−12 = −2.

Here is a graph of x%3: enter image description here Here is a graph of x%-3: enter image description here