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
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)
:
C: -5 % -3 == -2
rem: -5 rem -3 == -2
Y + X rem Y: -3 + -5 rem -3 == -5 !! wrong !!
The alternative implementations for the modulo operator use floored division and Euclidean division. The results for those are
flooring division: -5 mod -3 == -2
euclidean division: -5 mod -3 == 1
So
Y + X rem Y
doesn't reproduce any modulo operator for X < 0 and Y < 0.
And rem
works as expected -- it's using truncated division.
Erlang remainder not works with negative numbers, so you have to write your own function for negative parameters.