Skip to content

Instantly share code, notes, and snippets.

@marcoonroad
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcoonroad/150f423825a78e88dfb6 to your computer and use it in GitHub Desktop.
Save marcoonroad/150f423825a78e88dfb6 to your computer and use it in GitHub Desktop.
Reverse factorial at Lua...
-- defac as multi-dispatch pseudo-code
--
-- defac(x): defac(x / 1, 1) [ where x is Integer ]
-- defac(x, d): d - x [ where x = 1 ]
-- defac(x, d): error() [ where x < 1 ]
-- defac(x, d): defac(x / d, d + 1) [ where x > 1 ]
function defac (x, d)
d = d or 1
if x == 1 then
return d - 1
elseif x < 1 then
error ("Sorry, X isn't a factorial number.")
return
else
local r = defac (x / d, d + 1)
return r
end
end
-- test
print (defac (24)) --> 4
print (defac (720)) --> 6
print (defac (120)) --> 5
print (defac (121)) --> error!
-- end of script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment