How to factor using Python?

Lie Lie.1296 at gmail.com
Tue Mar 11 12:47:26 EDT 2008


On Mar 10, 12:08 pm, Nathan Pinno <MadComputer... at gmail.com> wrote:
> How do I factor a number? I mean how do I translate x! into proper
> Python code, so that it will always do the correct math?
>
> Thanks in advance,
> Nathan P.

Factorial algorithm is a very simple and common algorithm, and it's
one of the most basic of all recursive algorithm
def fact(x):
    return x * fact(x - 1)

That recursive function is very close to the basic definition of
factorials, that is
x! = x * (x - 1)!

If however, you expected x to be a real (float) value, you'd better
consider the gamma function as Mark Dickinson pointed out. Wikipedia
is a good start to create your gamma function:
http://en.wikipedia.org/wiki/Factorial
http://en.wikipedia.org/wiki/Gamma_function



More information about the Python-list mailing list