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

Elixir

Elixir Problem Overview


How can I calculate a number with an exponent in Elixir?

For example, 23 would return 8.

Elixir Solutions


Solution 1 - Elixir

Use the Erlang :math module

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

If you want an integer:

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

Solution 2 - Elixir

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 - Elixir

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)



Solution 4 - Elixir

Integer.pow/2

As of v1.12, Integer.pow/2 is the way to do this.

Solution 5 - Elixir

**/2

As of Elixir 1.13, ** is available.

> 2 ** 3 
8

Note: it returns a float if the exponent is less than 0.

Documentation

Solution 6 - Elixir

If the base is 2 and the power is an integer, you can do a left bitshift using the function Bitwise.bsl. For example, 23 can be calculated with:

> Bitwise.bsl(1, 3)
8

Solution 7 - Elixir

Tis works - it will be great when I learn enough to know exactly why it works - probably something to do with eval under the covers:

defmodule Example do
  require Integer

  def do_it(list) do
    list
    |> Enum.reject(&Integer.is_odd(&1))
    |> Enum.map(&(:math.pow(&1,3)))
  end
    
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan LongView Question on Stackoverflow
Solution 1 - ElixirNathan LongView Answer on Stackoverflow
Solution 2 - ElixirPaweł ObrokView Answer on Stackoverflow
Solution 3 - ElixirmarkusheiligView Answer on Stackoverflow
Solution 4 - ElixirNathan LongView Answer on Stackoverflow
Solution 5 - ElixirNathan WillsonView Answer on Stackoverflow
Solution 6 - ElixirlegosciaView Answer on Stackoverflow
Solution 7 - ElixirseagraphView Answer on Stackoverflow