Modulo operation(%) with negative numbers in Python3 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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 ?

28th Oct 2020, 7:35 AM
Armina
Armina - avatar
4 Answers
+ 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 😊
28th Oct 2020, 8:45 AM
Hacker Badshah
Hacker Badshah - avatar
+ 1
Coder Kitten Thanks for a million time for your explanation.🙏🏻🙏🏻 I got it now
28th Oct 2020, 12:22 PM
Armina
Armina - avatar
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?
28th Oct 2020, 8:26 AM
Armina
Armina - avatar
0
Hacker Badshah Thanks alot for your help 🙏🏻
28th Oct 2020, 8:48 AM
Armina
Armina - avatar