r/learnjava • • 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

31 comments sorted by

View all comments

1

u/Blackheart595 Oct 30 '16

7 % 3 == 1. That's because 7 / 3 == 2 if you round the result down, but 2 * 3 == 6, so there's still 1 missing. Similarily, 18 % 7 == 4 because 18 == 2 * 7 + 4.

Actually, as you seem to have some difficulties with English, try reading these wikipedia articles here and here in your language, it will probably explain everything you need.

1

u/[deleted] Oct 30 '16

Nope, I speak near fluent level, it's just that I'm tired as of right now. The reason why I didn't understand modulo is because our teacher used it in finding out a certain digit in a tri-digit number but she didn't really expand on that and when I tried asking her for some help she just outright ignored me.

1

u/salvagestuff Oct 30 '16

When using modulo for finding out digits, it is pretty much all about divisions of 10.

In your example, (n/100)%10 what it does is bring the digit from the hundreds place to the end of the number. The modulo 10 then returns the very last digit.

Lets say that n = 6543

(6543/100)%10

The division of 100 gives you back 65 (remember int division drops the decimal places).

65%10 will return 5 because that is not divisible by 10 while anything in front of the 5 is divisible by 10.

If I wanted the 10's I would do (n/10)%10

(6543/10)%10 654%10 = 4

If I wanted the thousands it would be (n/1000)%10

(6543/1000)%10 6%10 = 6

If I wanted the last digit it would be n%10

If you wanted to print all numbers out it could look like this.

System.out.println("Thousands: " + (n/1000)%10 + " Hundreds:" + (n/100)%10 + " Tens:" + (n/10)%10 + " ones:"+ n%10);

I hope that makes sense.