Factorial function: Difference between revisions

From EggeWiki
m (Created page with '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 f…')
 
mNo edit summary
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
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.
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">
<geshi lang="ruby">
def factorial(n)
def factorial(n)
Line 9: Line 10:
</geshi>
</geshi>


=== Python ===
<geshi lang="python">
<geshi lang="python">
fac = lambda n:reduce(lambda a,b:a*(b+1),range(n),1)
fac = lambda n:reduce(lambda a,b:a*(b+1),range(n),1)
Line 15: 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 19: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