I'm brand new to Erlang. How do you do modulo (get the remainder of a division)? It's % in most C-like languages, but that designates a comment in Erlang.
Several people answered with rem, which in most cases is fine. But I'm revisiting this because now I need to use negative numbers and rem gives you the remainder of a division, which is not the same as modulo for negative numbers.
The above Y + X rem Y seems to be wrong: either (Y + X) rem Y or Y + (X rem Y) yield incorrect results. Ex: let Y=3. If X=-4, the first form returns -1, if X=-3 the second form returns 3, none of which is in [0;3[.
I use this instead:
According to this blog post, it's
rem
.The accepted answer is wrong.
rem
behaves exactly like the%
operator in modern C. It uses truncated division.The accepted answer fails for X<0 and Y<0. Consider
mod(-5,-3)
:The alternative implementations for the modulo operator use floored division and Euclidean division. The results for those are
So
doesn't reproduce any modulo operator for X < 0 and Y < 0.
And
rem
works as expected -- it's using truncated division.The erlang modulo operator is
rem
In Erlang, 5 rem 3. gives 2, and -5 rem 3. gives -2. If I understand your question, you would want -5 rem 3. to give 1 instead, since -5 = -2 * 3 + 1.
Does this do what you want?
Erlang remainder not works with negative numbers, so you have to write your own function for negative parameters.