31 lines
820 B
Plaintext
31 lines
820 B
Plaintext
local bigint = require "pluto:bigint"
|
|
|
|
class Factorial
|
|
static function iterative(n)
|
|
local fact = bigint.new(1)
|
|
if n < 2 then return fact end
|
|
for i = 2, n do fact *= bigint.new(i) end
|
|
return fact
|
|
end
|
|
|
|
static function recursive(n)
|
|
if n < 2 then return bigint.new(1) end
|
|
return bigint.new(n) * Factorial.recursive(n - 1)
|
|
end
|
|
end
|
|
|
|
local function commatize(n)
|
|
local s = n:tostring()
|
|
local zero = bigint.new(0)
|
|
if n < zero then s = s:sub(2) end
|
|
for i = #s - 3, 1, -3 do
|
|
s = s:sub(1, i) .. "," .. s:sub(i + 1)
|
|
end
|
|
if n >= zero then return s end
|
|
return "-" .. s
|
|
end
|
|
|
|
local n = 24
|
|
print($"Factorial({n}) iterative -> {commatize(Factorial.iterative(n))}")
|
|
print($"Factorial({n}) recursive -> {commatize(Factorial.recursive(n))}")
|