Factorials
M-a-S
NO-MAIL at hotmail.com
Sat Sep 20 03:13:54 EDT 2003
> "Andrew Wilkinson" <ajw126 at NOSPAMyork.ac.uk> wrote in message
> >
> > def fac(n):
> > return reduce(long.__mul__, range(1,n+1), 1L)
> >
> > ..would probably be a bit quicker. I'm not sure how much quicker though.
> >
> > Anyway, hope this is of some use,
> > Regards,
> > Andrew Wilkinson
def factorial_rec(n):
if n <= 1:
return 1
else:
return n*factorial_rec(n-1)
def factorial_iter(n):
s = 1
for i in range(2,n+1):
s *= i
return s
def factorial_rdc(n):
return reduce(long.__mul__, range(1,n+1), 1L)
Best times (seconds) on Compaq 5430US, Pentium 4, 1.8GHz, 512MB
Windows XP, Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Calculations of 950!, 1000 times each (xrange(1000)) --
recursion ..... 8.01
reduction ..... 4.20
iteration ..... 3.79
M-a-S
More information about the Python-list
mailing list