What is modulus function ???🤔 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is modulus function ???🤔

how does it work🤔

27th May 2017, 6:45 PM
sandeep raj
sandeep raj - avatar
6 Answers
+ 10
Check up on modular clock arithmetics. Basically in x mod y, think of a clock, it will have values of 0 to (y-1) in it. We are going to spin the clock x times and wherever it lands is our result. 10 mod 4, our clock will have 0, 1, 2, 3. Spin it 10 times clockwise, it will end up at 2, and that is what 10 mod 4 gives us. And hence, this also means that in (x mod y), the answer will NEVER be larger than or same as y.
27th May 2017, 7:18 PM
Wen Qin
Wen Qin - avatar
+ 8
@Wen Qin That is probably the dankest explanation for modular arithmetic I've ever seen.
28th May 2017, 1:39 PM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Wow I never knew there was a clock for modulus
28th May 2017, 11:43 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 3
@Isabel If you set your modulus to return a decimal, yes. Otherwise, Modulus function always returns the floor (round down) of a result.
3rd Oct 2017, 10:34 PM
Wen Qin
Wen Qin - avatar
0
Means that when I have 1.25 mod 0.5 and spin the clock 0.5 times I land on 0.25?
3rd Oct 2017, 1:13 PM
Isabel Hohmann
Isabel Hohmann - avatar
0
Simply gives you the REMAINDER of the division. In programming generally the % sign is used as modulus operator. 42%10 == 2 19%5 == 4 Can be used with not whole numbers: 96.25%1.0 == 0.25 0.7%0.2 == 0.1 The result is of course between 0 and the number you mod with, as remainder must be less than the divisor. Typical usage is, when you check whether a number is a divisor of another or not, or whether a number is a multiple of another (same): int a = 50; //or whatever number if (a % 2 == 0) { //executes only if 'a' is even } Modulus can also be used for categorizing stuff (with numeric id's or hashcodes) into categories. For example, you have a game and players can join. You have three groups they shall be added to. Whenever a player joins, he gets an increasing number starting from 0, so you will have player 0,1,2,3,4... and then you can make each player join the group N%3 (== 0,1 or 2). Similar strategy is used for hash searching. For example, imagine you have three boxes and are asked to find a value for a key. You also know the hashcode of the key, let it be N. You will know, that the value for the given key is in the box with index N%3, because you put it there before, calculating the same box index. Hashmaps (dictionaries) use this strategy for storage and lookups. Of course this asserts, that the keys always have the same hashcode or you are tricky enough, but that's another story. This is why objects have hashCode in the first place by the way :)
2nd Jun 2018, 12:49 AM
Magyar Dávid
Magyar Dávid - avatar