r/learnjava • u/[deleted] • Oct 30 '16
What the HELL is a modulo?
I have a test tomorrow, in the test one of the questions will be to seperate a number from a 3 digit number, say I have 641, I need to know how to print out 6,4 and 1 seperately.
What the hell do I do ? The teacher is so bad I couldn't understand a word she said and neither did my class, we already complained about her but this isn't the issue, the issue is that I have no easy answers on the internet for what the modulo is.
Why does doing (n/100)%10; print out the hundred digit ? I have no idea how this works, please go easy on me.
0
Upvotes
3
u/g00glen00b Oct 30 '16
The modulo operator returns the "remainder" of a division. If you think back to your early days at school, when you first learned dividing using long divisions, you learned that for 14/4 the result is 3 and the remainder is 2. Because "4" fits "3" times in '14", but then you still have a remainder of "2" so that:
Now, why do they suggest using the modulo operator to get the different numbers (6, 4, 1). Well, let's start from the right. If we divide 641/10, we know that it fits 64 times inside 641 and the remainder is 1. In java terms this is:
Now, you can repeat the same process over and over again, however, we need to "shift" the number a bit. For example, if we want to know the second digit, we first divide 641 by 10, so that we only have 64. Now we can just retrieve the last digit again by using the modulo operator:
Now, you should start to see a system here. You can keep doing this trick over and over again, but in stead of dividing by 10, you divide by 100, 1000, 10000, 100000, ... and you get the next digit every time. In your case, the left digit can be retrieved by using:
In this case, it's pretty "useless" to use the modulo operator, because if you have a number with only 3 digits, dividing by 100 will already yield the left most digit. However, let's say that our number was 1234, then we would get: