0

What does the MOD operator really mean? “%”

I have used this symbol many times in coding and know that it gives a remainder.. but I do not really know what that means? Why is a remainder important? What’s the importance of the modula operator? What is its potential in code?

6th Feb 2022, 7:41 PM
Annei ❤️
Annei ❤️ - avatar
3 Answers
+ 3
You want to share 20 pieces of candy among 3 people. Best you can do is to give 6 to each. 2 will be left over—the remainder. If it's 2 o'clock now and you wait 14 hours, it'll be 4 o'clock—not 16 o'clock. 4 o'clock is the remainder of when you divide 16 o'clock by 12. Modulo turns calculations on the infinitely long number line into calculations "on clocks". If you do arbitrary maths and then do %30 at the end of it, it's like you took the number line and wrapped it around a clock with 30 hours. When you start counting in a %30 context, you start at 0, count until 29, then go back to 0 again. % is so ubiquitous in programming, it's hard to nail down a single use case. `rand()` returns a random number between 0 and infinity, but you only want numbers from 0 to 99? Do `rand()%100`.
7th Feb 2022, 1:26 AM
Schindlabua
Schindlabua - avatar
+ 4
It's an arithmatic operator, just like /, *, +, - Gives reminder. One simple use is "to find a integer is even or odd "like Number%2==0 : even else odd.
6th Feb 2022, 8:18 PM
Jayakrishna 🇮🇳
Jayakrishna 🇮🇳 - avatar
+ 2
Among its many uses, I use modulo most often to model conditions when numbers count up to a maximum and then wrap around back to the beginning, like: * hours %12, %24 * minutes, seconds %60 * months %12 * day of the week %7 * units digit %10 * base conversions %base * x, y screen coordinates %width, %height * sawtooth waveform %amplitude * ring buffer index %bufsiz In Euler's algorithm to find GCD, he used repeated subtraction until a remainder is found. But modulo optimizes it by using division as a shortcut to repeated subtraction, and gets straight to the remainder.
7th Feb 2022, 5:47 AM
Brian
Brian - avatar