Calculating factorial
Tim Hochberg
tim.hochberg at ieee.org
Wed Dec 6 17:11:11 CET 2000
"Roger Hansen" <rogerha at ifi.uio.no> wrote in message
news:ya0vgsx3h2f.fsf at levding.ifi.uio.no...
[SNIP]
> Agree! it's a nice version. But I think the recursive version is even
> clearer.
>
> >>> def fact(n):
> ... if n > 1:
> ... return n*fact(n-1)
> ... return 1
> ...
> >>> fact(4)
> 24
>
> You can change line 3 with
> ... return long(n)*fact(n-1)
>
> and you have long integers
Alternatively, change "return 1" to "return 1L". Unfortunately, the
recursive version has the drawback that it run's into python's recursion
limit (at around 1000 on my machine).
One more entry that I like is:
def factorial(n):
result = 1L
while n:
result *= n
n -= 1
return result
It's not any faster than the other choices, but it has the dubious,
theoretical distinction of using less memory than all but the xrange version
and in theory could handle numbers above sys.maxint (crude estimates
indicate that sys.maxint! would take something around a year to compute on
my machine, discounting memory issues).
-tim
More information about the Python-list
mailing list