Factorial function: Difference between revisions
mNo edit summary |
mNo edit summary |
||
Line 17: | Line 17: | ||
print "%i\t%i" % (i,fac(i-1)/2) | print "%i\t%i" % (i,fac(i-1)/2) | ||
</geshi> | </geshi> | ||
These of course are the ''naive'' implementations, and work fine in Ruby and Python because they have decent BigInteger support. For a 'real' algorithm, you should use one of the ones found here: http://www.luschny.de/math/factorial/FastFactorialFunctions.htm | |||
[[Category:Python]] | [[Category:Python]] | ||
[[Category:Ruby]] | [[Category:Ruby]] |
Latest revision as of 23:06, 10 August 2009
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>
These of course are the naive implementations, and work fine in Ruby and Python because they have decent BigInteger support. For a 'real' algorithm, you should use one of the ones found here: http://www.luschny.de/math/factorial/FastFactorialFunctions.htm