When I try to run this:
echo -1 %% 6
it prints 3, however it should evidently be 5. Does the %% not work with negative numbers? Am I missing something?I've never seen the %% operator. I've always used mod:
echo -1 mod 6
But this gives -1, not 5. Perhaps this PR is relevant: https://github.com/nim-lang/Nim/pull/7118
Like all operators ending with %, %% treats its arguments as unsigned numbers. This comes from a time when Nim didn't have unsigned numbers yet. -1 unsigned is 18446744073709551615 and 18446744073709551615 mod 6 is 3.
Note that for most programming language remainder (math) is called modulo (programming) which does not help.
Nim really should have a rem operator and a mod operator as they are slightly different:
https://en.wikipedia.org/wiki/Modulo_operation
If you want python's mod operator:
proc pythonMod(n, M: int): int = ((n mod M) + M) mod M
assert pythonMod(1, -4) == -3
assert pythonMod(-1, 4) == 3
assert pythonMod(-1, -4) == -1
assert pythonMod(1, 4) == 1