41
A
回答
45
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)
相關問題
- 1. 如何提高指數的權力?
- 2. 提高一個數字的權力;重複單詞
- 3. 提高一個複雜的數字,以任何權力在c語言
- 4. 提高權力給我的問題
- 5. 我將如何在java中實現高效的權力方法
- 6. 如何使用數學類提高數字的力量
- 7. 如何提高一個int或長在C++電力
- 8. 如何在Elixir中生成一個隨機數字?
- 9. 如何在Crystal Reports的Crystal語法中將數字提高到一個數字?
- 10. C提高到他們的位置的權力的數字的總和
- 11. 我如何得到一個高達一個權利的股利
- 12. 推力::序列 - 如何提高每個N元素後一步
- 13. 我試圖提高數字來他們連續的權力和我的代碼是不工作
- 14. 我想用Java創建一個「*」的權力金字塔。
- 15. 如何提高我的Flex/Java堆棧的生產力?
- 16. 我如何給div的平等權力
- 17. 如何檢查一個字符串是否在Elixir中爲空
- 18. 權力在字符串中的C#
- 19. Javascript:爲什麼我的數字沒有被提升到第n個權力並被推送到我的數組?
- 20. 在vb.net我如何提高另一個控件的事件
- 21. 如何在RichtextBox中顯示權力?
- 22. 如何在Access VBA + SQL開發中提高生產力?
- 23. 如何在GWT Maven多模塊項目中提高生產力
- 24. 我如何從一個URL使用PHP提取一個數字
- 25. Ecto + Elixir:我如何查詢hashmap字段?
- 26. 如何在具有計數能力的另一個字典中創建字典?
- 27. 如何從一個字符串中提取一個數字C
- 28. 如何讓一個數字成爲一個力量?
- 29. 如何從Elixir中的元組列表中提取整數?
- 30. 在Elixir中,我如何遍歷另一個循環中的列表?
非常好!用這個Erlang翻譯代替':math.pow'的當前實現將會很好。 https://github.com/erlang/otp –
當前:math.pow實現是一個NIF我想,是不是? – markusheilig