-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmathext.lua
68 lines (63 loc) · 1.57 KB
/
mathext.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
local M = {}
function M.round(n)
if math.type(n) == "float" then
local r
local f = math.floor(n)
local c = math.ceil(n)
if n >= f + 0.5 then
r = c
elseif n < c - 0.5 then
r = f
end
r = math.tointeger(r)
return r
else
return n
end
end
function M.fact(n)
if math.type(n) == "float" then
return error("expected int, got float")
else
if n == 0 then
return 1
else
return n * M.fact(n - 1)
end
end
end
function M.perm(n, r)
if math.type(n) == "float" or math.type(r) == "float" then
return error("expected int, got float")
else
if r > n then
return error("arg #1 < arg #2, arg #1 expected to be > arg #2")
else
r = n - r
n = M.fact(n)
r = M.fact(r)
local prob = n / r
prob = math.tointeger(prob)
return prob
end
end
end
function M.comb(n, r)
if math.type(n) == "float" or math.type(r) == "float" then
return error("expected int, got float")
else
if r > n then
return error("arg #1 < arg #2, arg #1 expected to be > arg #2")
else
local dif = n - r
dif = M.fact(dif)
n = M.fact(n)
r = M.fact(r)
r = r * dif
local prob = n / r
prob = math.tointeger(prob)
return prob
end
end
end
return M