Correct modulo for negative numbers
It's often annoying that the result of the modulo operation gives the same sign as the first operand. E.g. -5 3%
gives -2
instead of 1
. More often than not you want the latter. The naive fix is to apply modulo, add the divisor once and apply modulo again:
3%3+3%
But that's long and ugly. Instead, we can use the fact that array indexing is always modular and does work correctly with negative indices. So we just turn the divisor into a range and access that:
3,=
Applied to -5
, this gives 1
as expected. And it's only one byte longer than the built-in %
!
If the modulus is a power of 2, you can save another byte using bitwise arihmetic (which is also a lot faster). Compare:
32,=
31&
For the special case of 65536 == 2^16
another byte can be saved by making use of the wrapping behaviour of the character type:
ci