How do I raise a number to a power in Elixir?

Solution 1:

Use the Erlang :math module

:math.pow(2,3) #=> 8.0

If you want an integer:

:math.pow(2,3) |> round #=> 8

Solution 2:

Erlang's :math.pow has some limitations, for example it will not allow really high integer exponents:

iex(10)> :math.pow(2, 10000)
** (ArithmeticError) bad argument in arithmetic expression

You can easily reimplement a fast algorithm for computing exponentials that will work with the arbitrarily large integers provided by the runtime:

defmodule Pow do
  require Integer

  def pow(_, 0), do: 1
  def pow(x, n) when Integer.is_odd(n), do: x * pow(x, n - 1)
  def pow(x, n) do
    result = pow(x, div(n, 2))
    result * result
  end
end

iex(9)> Pow.pow(2, 10000)
19950631168807583848837421626835850838234968318861924548520089498529438830...

Solution 3:

Here is a tail call optimized implementation of the power function:

def  pow(n, k), do: pow(n, k, 1)        
defp pow(_, 0, acc), do: acc
defp pow(n, k, acc), do: pow(n, k - 1, n * acc)