summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHybridDog <ovvv@web.de>2019-03-05 10:11:21 +0100
committerLoïc Blot <nerzhul@users.noreply.github.com>2019-03-05 10:11:21 +0100
commita7c5dc50e5445c3aa3b45ea4be48fc179bd4cce8 (patch)
tree9ece096c4d7c38a3ac9079f8a53c8c9b41b0df30
parent250420e56685b597088596a5498f5babcf6de5f9 (diff)
downloadminetest-a7c5dc50e5445c3aa3b45ea4be48fc179bd4cce8.tar.gz
minetest-a7c5dc50e5445c3aa3b45ea4be48fc179bd4cce8.tar.bz2
minetest-a7c5dc50e5445c3aa3b45ea4be48fc179bd4cce8.zip
Add math.factorial (#8298)
-rw-r--r--builtin/common/misc_helpers.lua14
-rw-r--r--doc/lua_api.txt1
2 files changed, 15 insertions, 0 deletions
diff --git a/builtin/common/misc_helpers.lua b/builtin/common/misc_helpers.lua
index e250b0ed1..25632b4ca 100644
--- a/builtin/common/misc_helpers.lua
+++ b/builtin/common/misc_helpers.lua
@@ -244,6 +244,20 @@ function math.sign(x, tolerance)
end
--------------------------------------------------------------------------------
+function math.factorial(x)
+ assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
+ if x >= 171 then
+ -- 171! is greater than the biggest double, no need to calculate
+ return math.huge
+ end
+ local v = 1
+ for k = 2, x do
+ v = v * k
+ end
+ return v
+end
+
+--------------------------------------------------------------------------------
function get_last_folder(text,count)
local parts = text:split(DIR_DELIM)
diff --git a/doc/lua_api.txt b/doc/lua_api.txt
index 05ea6b4bc..593ab50dd 100644
--- a/doc/lua_api.txt
+++ b/doc/lua_api.txt
@@ -2378,6 +2378,7 @@ Helper functions
* tolerance: number, default: `0.0`
* If the absolute value of `x` is within the `tolerance` or `x` is NaN,
`0` is returned.
+* `math.factorial(x)`: returns the factorial of `x`
* `string.split(str, separator, include_empty, max_splits, sep_is_pattern)`
* `separator`: string, default: `","`
* `include_empty`: boolean, default: `false`