2015-08-15 59 views

回答

45

如果你想要一個整數使用Erlang :math module

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

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

Erlang的:math.pow有一定的侷限性,例如它不會允許真正的高整數功率:

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

您可以輕鬆地重新實現了計算能力的快速算法,將與由運行時提供的任意大整數的工作:

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... 
3

下面是冪函數的尾調用優化的實現:

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) 
+0

非常好!用這個Erlang翻譯代替':math.pow'的當前實現將會很好。 https://github.com/erlang/otp –

+0

當前:math.pow實現是一個NIF我想,是不是? – markusheilig