How do you do modulo or remainder in Erlang?

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.


Solution 1:

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?

mod(X,Y) when X > 0 -> X rem Y;
mod(X,Y) when X < 0 -> Y + X rem Y;
mod(0,Y) -> 0.

Solution 2:

The erlang modulo operator is rem

Eshell V5.6.4  (abort with ^G)
1> 97 rem 10.
7

Solution 3:

I used the following in elixir:

defp mod(x,y) when x > 0, do: rem(x, y);
defp mod(x,y) when x < 0, do: rem(x, y) + y;
defp mod(0,_y), do: 0