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.
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 %.
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.
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.
The erlang modulo operator is rem
Eshell V5.6.4 (abort with ^G) 1> 97 rem 10. 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With