tags:

views:

1623

answers:

7

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.

+1  A: 

According to this blog post, it's rem.

Jon Skeet
+4  A: 

The erlang modulo operator is rem

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

Google, first hit:

“The operator for modular arithmetic in Erlang is rem (for remainder).”

Bombe
First hit and the result doesn't match what was looked for.
JUST MY correct OPINION
A: 

I believe I read somewhere Erlang has 3, namely*:

  1. quotient
  2. remainder
  3. modulo

* names could be wrong, using what I have from Scheme, that still has another 2!

leppie
A: 

Erlang remainder not works with negative numbers, so you have to write your own function for negative parameters.

JLarky
+3  A: 

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.
grifaton
This will work. But is there really nothing distributed with erlang that does this?
Matt
Not according to the erlang reference manual: http://erlang.org/doc/reference_manual/expressions.html (section 6.12)
grifaton
Alternatively: mod(X,Y)->(X rem Y + Y) rem Y.
Koistinen
A: 

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:

% Returns the positive remainder of the division of X by Y, in [0;Y[. 
% In Erlang, -5 rem 3 is -2, whereas this function will return 1,  
% since -5 =-2 * 3 + 1.

modulo(X,Y) when X > 0 ->   
   X rem Y;

modulo(X,Y) when X < 0 ->   
    K = (-X div Y)+1,
    PositiveX = X + K*Y,
    PositiveX rem Y;

modulo(0,_Y) -> 
    0.

Hope this helps,

Olivier Boudeville.