What’s the difference? Most of the time, nothing.
If both operands are positive, modulus and remainder are equivalent.
16 modulo 7 is 2, and the remainder of 16 divided by 7 is 2.
In some calculations used to find an index in a PowerShell array using negative operands, modulus and remainder are mathematically different, but functionally equivalent.
Sometimes in PowerShell, the “wrong” result works anyway.
For example, given the following function:
We are using % to calculate the index to the correct day of the week in the array. If the starting day (day zero) is on Sunday, day 16 will be on 16 modulo 7, or 2, which points to Tuesday.
If we count backwards 16 days from Sunday, -16 modulo 7 is 5, which points to Friday.
But % doesn’t do modulo, it finds the remainder, and the remainder of -16 divided by 7 is -2.
But it works anyway. In PowerShell, $WeekDays points to the sixth element from the start of the array, and $WeekDays[-2] points to the second element from the end of the array. In an array with 7 elements, both of these point to the same element.
Modulus and remainder handle negative dividends differently
If we need to use the results from negative operands anywhere other than as the index of an array, we need to be aware of the difference between modulus and remainder, and understand that % performs a remainder operation.
For positive operands, modulus and remainder follow the same pattern.
The difference is in what happens to that pattern when we carry on past zero.
For modulus, the pattern continues unchanged.
For remainder, the pattern reverses, and becomes negative.
Changing the sign of the divisor does not change the result of either modulus or remainder.