Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Does RBXLua have factorials?

Hey guys,

I was in the middle of writing a code until I realised that I needed to use factorials (x!) to carry out a calculation. I noticed that the Wiki didn't help much. Does anyone know how to use factorials in Lua?

If you're unsure by what I mean with "factorial", it is a mathematical operation where x is continuously multiplied by x-1 until x=1

Example:

(4! = 4 x 3 x 2 x 1 = 24) and (5! = 5 x 4! = 5 x 24 = 120 (or 5 x 4 x 3 x 2 x 1))

2 answers

While other answer works just fine, I'm not sure why would you complicate it like that, and make it slower.

This function does exactly same, but is faster and simpler:

function fact( n )
	local ret = 1
	
	-- Simply loop through all the numbers, and multiply them together
	for num=1, n do
		ret = ret * num
	end

	return ret
end

Here is both function comparision: https://repl.it/CAUb

I don't believe Lua comes with such a function, but a quick search came up with this:

    function fact (n)
      if n == 0 then
        return 1
      else
        return n * fact(n-1)
      end
    end

Which you can just use like so:

print(fact(5)) -- Prints '120'

Also, I have now been educated on factorials. I guess that's good?

2 comments

0

Lua functions are slooowwwwww. Use with caution!

0

Not tail recursive! B+. /s

This discussion is preserved as it was. New answers, comments, and votes are closed.