Remainder/Modulus Operator Confusion and explanation!

The first time I used the remainder operator I got really confused, specially when the left value is smaller than the right value because it always returns the left value no matter what. For instance:
30 % 60 = 30

If we solve the division it will give us a remainder of 0, because 30 / 60 = 0.5, Why it is returning 30?

I searched the internet and I found this weird operation in the microsoft docs:
a % b = a - (a / b) * b

Even if you’re not a math genius you can clearly see that the operation is silly at best, the result will always be 0, so, What is missing?

Well, after almost an hour of reading I found this: a - trunc(a / b) * b
The operation truncates(floor) the division value, so, we get this:
30 - trunc(30 / 60) * 60
30 - trunc(0.5) * 60
30 - 0 * 60
30 - 0 = 30

If we use the same operation with the challenge (63 % 4):
63 - trunc(63 / 4) * 4
63 - trunc(15.75) * 4
63 - 15 * 4;
63 - 60 = 3

Why is this important?
This means that the Remainder operator can be really versatile, you can use it for timers:

Time % 60 = Time in seconds or minutes. Perfect for display purposes.

You can use it to count turns and assign them as the lesson suggests:

TotalTurns % NumberOfPlayers
Turn ends
Total turns + 1

You can get really creative and use it to tell an enemy which ability will it use next:

Abilitiy to use = Game time % Total number of abilities
Array of abilities[ability to use]

Of course, there are far more uses for this, but it really helps to understand what is going on in the background, I only used the operator for timers, now that I know exactly what it’s going on, my mind immediatly flooded with ideas and ways to optimize and clean my code.

1 Like

Great explanation @Yee :slight_smile:
The remainder operator really is an incredibly useful tool to have in your coding arsenal. It’s great to see you taking the extra time to really dig in to how it works, so that you can understand it better.

You’re right that it has a myriad of applications and can make using arrays a lot easier.

1 Like