Factorial function: Difference between revisions
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 |
||
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) |
Revision as of 03:44, 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>