+ 8

# WHY? 4%10=4 -4%10=6

10 ответов

+ 19

Because in Python the remainder must be less than the divisor AND positive (Java and javascript choose the sign of the numerator instead).
In Python, taking the modulo formula as:
x=qc + r (total = q*divisor + remainder)
Rewritten as:
x - qc = r (total - q*divisor = remainder)
You know 'x' and 'c', you're trying to find 'r', so all you can change is 'q'.
For your examples:
1) 4%10=4
4 - 0(10) = 4 (q=0)
2) -4%10=6
-4 - (-1*10) = 6 (q=-1)
Reference, with additional negative examples:
http://math.stackexchange.com/questions/519845/modulo-of-a-negative-number
edit: adding 2 codes due to another question...
https://code.sololearn.com/c7o8hur596jS/?ref=app
https://code.sololearn.com/c0VcyWYMEfed/?ref=app

+ 4

Good to know. In C++ and Javascript, negative numbers modulo m produce a number between -(m-1) and 0 instead of doing a true modulo. And I dislike it, I have to do (n%m + m)%m as a workaround.

+ 3

It's just the matter of mathematics.
a % d = r ,means:
a = (k * d) + r ,that k is an integer and r is a positive integer
so we have:
-4 = (k * 10) + r
now if we consider k = -1,
-4 = -10 + r ==> r = 6

+ 3

still don't understand. how do I solve this
7%(5//2)

+ 2

@Kirk Schafer. Thank you. Excellent answer! I understand.
But unfortunately, I believe this is a BUG in Python, because I lost time!
In C++, Java (and other) remainder of division is correct. In Python, uses the formula " x=qc + r (total = q*divisor + remainder)" without knowing it, the code causes the program error.
My son was not able to solve this simple school problem (find the maximum negative number and not finishing 4. http://www.sololearn.com/app/python/playground/cS6vzGj2g6mf/ ).
My solution to this problem be SURE to use abs:
abs (x)%y
It would be nice if it took into account in this lesson and drew the attention of the students.
P.S. Sorry for my English .

+ 1

da jopa eto, zabey

0

because 4 can not divided completely, so in 0 times division it will give 4 as a remainder.
-4%10=6
-4+10=6

0

but shouldn't 4/10 be producing a decimal quotent n a reminder of zero?

0

@Sidi Victor to get the answer type in : print(7%(5///2)). Enter that without codes for solving it. They have left out the part about print command that must be placed before anything that is to be displayed.

0

Why does Python assume that q=-1? Is it to make the remainder positive AND less than the divisor? If that's so, then does that mean that Python looks for the closest number to the quotient that will give a remainder that is positive AND less than the divisor? Because -4/10 has a quotient of 0. So that means if Python finds it to be -1, it looks for the closest number to 0 to create a remainder that satisfies the rules...?