0

What does this modulo operator actually do?

18th Jul 2016, 7:33 AM
Kajal Piwal
Kajal Piwal - avatar
4 Respostas
+ 5
In simple words, a%b gives the remainder when a is divided by b Most students are taught that "Dividend = Divisor * Quotient + Remainder" In more sophisticated language, this is the Division Algorithm : For any integers a and b such that b is non-zero, there exist unique integers q and r such that a = b*q + r where 0<=r<b So a%b gives r For example, 9 = 2*4 + 1 So 9%2 = 1 Another way to think about it is something like this. Imagine you have 26 apples and you want to pack them in groups of 7. 26%7 will give you the number of apples left after all the groupings are done. In this case, you will get 3 groups of 7 apples accounting for 21 apples with 5 apples left. These 5 apples cannot be packed into groups of 7 as 5<7 So 26 = 7*3 + 5 This means 26%7 = 5 Note that making 0 groups is allowed, but the number of remaining apples should be less than that in each group.
19th Jan 2017, 12:27 PM
Dhaval Furia
Dhaval Furia - avatar
0
I'm not sure what "this" you're referring to, but a modulo operator gives you what is leftover after an integer division. For example: 17 // 5 = 3 because 5 fits into 17 three times (3 * 5 = 15) and 17 % 5 = 2 because that it what is left "unused" after integer division: 17 - (3 * 5) = 2.
18th Jul 2016, 2:16 PM
John Davies
0
It can also help you rotate through certain values. Example: import turtle t = turtle.Pen() colors = ["red", "blue", "yellow", "orange"] for x in range (100): t.pencolor(colors[x%4]) t.left(90) t.forward(x) As you can see, the modulo operator is used in this for loop and is rotating through the different colors in the variable colors. It is rotating because as x increases, the remainder changes. For example: when x is equal to 4 the remainder is 0 because 4%4 is 0. then when x is equal to 5 the remainder is 1 because 5%4 is 1. The remainder keeps growing larger until it reaches a multiple of 4, which is uncoicidentally the number of colors there are in the variable colors, then the remainder becomes 0 again. Since each colors represent a number, the colors are rotated through. In this case, red is represented by the number 0 so when the remainder of x % 4 is equal to 0 the color changes to red and then to blue when x grows by one and so on.
26th Jul 2016, 7:21 AM
Jason Li
Jason Li - avatar
0
% or modulo gives you the remainder. Simple example: 3 % 2 = 1 because 2 goes into 3 one time and there's a remainder of 1.
28th Jul 2016, 10:42 PM
daniel fancher
daniel fancher - avatar