Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do modulo or remainder in Erlang?

Tags:

modulo

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.

like image 975
Matt Avatar asked Dec 09 '08 15:12

Matt


People also ask

What is remainder modulo?

Modulo or Remainder Operator returns the remainder of the two numbers after division. If you are provided with two numbers, say A and B, A is the dividend and B is the divisor, A mod B is there a remainder of the division of A and B. Modulo operator is an arithmetical operator which is denoted by %.

How does mod () work?

The modulo operation (abbreviated “mod”, or “%” in many programming languages) is the remainder when dividing. For example, “5 mod 3 = 2” which means 2 is the remainder when you divide 5 by 3.


2 Answers

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. 
like image 173
grifaton Avatar answered Sep 22 '22 23:09

grifaton


The erlang modulo operator is rem

Eshell V5.6.4  (abort with ^G) 1> 97 rem 10. 7 
like image 31
Alnitak Avatar answered Sep 25 '22 23:09

Alnitak