0
Modulo operation(%) with negative numbers in Python3
Hi everyone, we have this simple operation in python where a is positive and b is negative (a%b)for example 17% -3 In python it will be -1 but the remainder is 2 like in c++ Can anyone tell me how python show this ouput ?
6 Antworten
+ 3
In Python % function always gives the output in the sign of denominator.
So that's how 17 % -3 is done in python:
17/-3 = -5.666 >> floor(-5.666) = -6
So 17%-3 == ((-6×-3)+( -1))%-3
Now (a+b)%c = [a%c + b%c]%c
So 17%-3 == ((-6×-3)+( -1))%-3
>>>[(-6×-3)%-3 + (-1%-3)]%-3
>>>[(0)+( -1)]%-3
>>>(-1)%-3 = -1
Hope It Helps You 😊
+ 1
Coder Kitten
Thanks for a million time for your explanation.🙏🏻🙏🏻
I got it now
0
Coder Kitten
Thanks alot for your explanation.
I just have a question. As i remember from high school, M can never be negetive , so here it is negative and therefore i can't understand it.
Class M is for positive M , isn't it?
0
Hacker Badshah
Thanks alot for your help 🙏🏻