Factorial function

From EggeWiki
Revision as of 23:44, 9 August 2009 by Brianegge (talk | contribs)

The Factorial factorial function can easily be created via a recursive function. Oddly, it's often not a built in function as are other mathematical operators. Here's a few implementations of the function, along with an example for each.

Ruby

<geshi lang="ruby"> def factorial(n)

 if n == 1 then 1 else n * factorial(n-1) end

end

(3..20).each { |n| c=(factorial(n-1)/2).to_s.gsub(/(\d)(?=\d{3}+(\.\d*)?$)/, '\1,'); puts "#{n}\t#{c}" } </geshi>

Python

<geshi lang="python"> fac = lambda n:reduce(lambda a,b:a*(b+1),range(n),1)

for i in range(3,21):

  print "%i\t%i" % (i,fac(i-1)/2)

</geshi>