Factorials

Not sure if an actual factorial command in AS. If not it’s very simply to write your own function for it. This is what I use


on fac(theNum)
set answer to 1
	repeat with i from 1 to theNum
		set answer to answer * i
	end repeat
	return answer
end fac

fac(5) -- returns 120


Hi, hendo.

It would be better for ‘answer’ to be local to the handler:

on fac(theNum)
	set answer to 1
	repeat with i from 1 to theNum
		set answer to answer * i
	end repeat
	return answer
end fac

fac(5) -- returns 120, every time!

There is also a recursive version:

on factorial(n)
	if n > 0 then
		return n * (factorial(n - 1))
	else
		return 1
	end if
end factorial

agreed, not sure why i stuck it out of the handler in the first place. Modifying now, thanks Nigel :slight_smile:

Another thing, I suppose, is that the first iteration of the repeat (multiplying 1 by 1) is superfluous. You could repeat with i from 2 to theNum. If theNum is 1, the repeat simply won’t be executed. :slight_smile:

That’s true because multiplying by 1 will not change regardless. Although in a function this small a difference in speed would be microscopic.