How do you do modulo or remainder in Erlang?

2019-03-14 06:15发布

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.

标签: erlang modulo
8条回答
相关推荐>>
2楼-- · 2019-03-14 06:35

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

Please don't downvote this because it's another language than the question. We all live the dream, because we all have the beam.

查看更多
smile是对你的礼貌
3楼-- · 2019-03-14 06:41
mod(A, B) when A > 0 -> A rem B;
mod(A, B) when A < 0 -> mod(A+B, B); 
mod(0, _) -> 0.

% console:
3> my:mod(-13, 5).
2
查看更多
登录 后发表回答