## Saturday, November 5, 2016

### PowerShell Modulus operator is a remainder operator, not a modulus operator

The percent sign in PowerShell is known as the modulus operator. But it is in fact not a modulus operator. It is a remainder operator.

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:

 function Get-DayofWeek ( \$StartDay = 0, \$Offset = 0 ) { \$Weekdays = "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" \$EndDay = ( \$StartDay + \$Offset ) % 7 return \$Weekdays[\$EndDay] } Get-DayofWeek -StartDay 0 -Offset  16 Get-DayofWeek -StartDay 0 -Offset -16

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[5] 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.

 % Dividend Divisor Modulus Remainder 7 3 1 1 6 3 0 0 5 3 2 2 4 3 1 1 3 3 0 0 2 3 2 2 1 3 1 1 0 3 0 0

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.

 % Dividend Divisor Modulus Remainder 7 3 1 1 6 3 0 0 5 3 2 2 4 3 1 1 3 3 0 0 2 3 2 2 1 3 1 1 0 3 0 0 -1 3 2 -1 -2 3 1 -2 -3 3 0 0 -4 3 2 -1 -5 3 1 -2 -6 3 0 0 -7 3 2 -1

Changing the sign of the divisor does not change the result of either modulus or remainder.

 % Dividend Divisor Modulus Remainder 7 -3 1 1 6 -3 0 0 5 -3 2 2 4 -3 1 1 3 -3 0 0 2 -3 2 2 1 -3 1 1 0 -3 0 0 -1 -3 2 -1 -2 -3 1 -2 -3 -3 0 0 -4 -3 2 -1 -5 -3 1 -2 -6 -3 0 0 -7 -3 2 -1