Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulo operator in Elixir

Tags:

modulo

elixir

How do I use the modulo operator in Elixir?

For example in Ruby you can do:

5 % 2 == 0

How does it differ from Ruby's modulo operator?

like image 821
dan-klasson Avatar asked Feb 20 '19 16:02

dan-klasson


People also ask

What is modulo operator example?

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.

How do you divide in Elixir?

In Elixir, division using the division operator (/) always results in a float no matter whether the operands are integers or floats. So 5 / 2 is 2.5 and 8 / 2 is 4.0. Javascript behaves similarly, but Javascript has a single numerical data type.

What is MOD () in C?

The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.

What is modulus operator in Java with example?

If both operands for %, the modulus operator have type int, then exprleft % exprright evaluates to the integer remainder. For example, 8 % 3 evaluates to 2 because 8 divided by 3 has a remainder of 2. When both operands have type int, the modulus operator (with both operands) evaluates to int.


2 Answers

For integers, use Kernel.rem/2:

iex(1)> rem(5, 2)
1
iex(2)> rem(5, 2) == 0
false

From the docs:

Computes the remainder of an integer division.

rem/2 uses truncated division, which means that the result will always have the sign of the dividend.

Raises an ArithmeticError exception if one of the arguments is not an integer, or when the divisor is 0.

The main differences compared to Ruby seem to be:

  1. rem only works with integers, but % changes its behavior completely depending on the datatype.
  2. The sign is negative for negative dividends in Elixir (the same as Ruby's remainder):

Ruby:

irb(main):001:0> -5 / 2
=> -3
irb(main):002:0> -5 % 2
=> 1
irb(main):003:0> -5.remainder(2)
=> -1

Elixir:

iex(1)> -5 / 2
-2.5
iex(2)> rem(-5, 2)
-1

Elixir's rem just uses Erlang's rem, so this related Erlang question may also be useful.

like image 128
Adam Millerchip Avatar answered Sep 22 '22 06:09

Adam Millerchip


Use rem/2 see: https://hexdocs.pm/elixir/Kernel.html#rem/2 So in Elixir your example becomes:

rem(5,2) == 0

which returns false

BTW what you wrote using % in Elixir simply starts a comment to the end of the line.

like image 44
GavinBrelstaff Avatar answered Sep 22 '22 06:09

GavinBrelstaff