How to factor using Python?

Mark Dickinson dickinsm at
Tue Mar 11 15:13:23 CET 2008

On Mar 10, 7:32 pm, Nathan Pinno <MadComputer... at> wrote:
> Thanks on the factoring bit, but I did mean factorial, not factoring.
> How do I code that correctly, so that I can figure the following
> equation out: cos(Pi * (z-1)! / z).

Is z an integer in this expression?  (Note: it's not an equation---
there's no equality sign.)  This looks suspiciously like
a formula that's supposed to be valid for real and possibly even
complex z, in which case what you're after is the gamma function.
(gamma(z) = (z-1)!).  The real version of this should certainly
be present in numpy/scipy, and possibly the complex version too.

If z really is supposed to be an integer then you should be aware
that evaluating the expression directly is going to give almost
no accuracy, for z greater than 30 or so: the absolute error in the
argument to cosine will likely be much larger than 2*pi, so that
the result of the cos() evaluation is meaningless.  You might be
better off computing w = (factorial(z-1) % (2*z)) as an integer;
then cos(pi*(z-1)!/z) can be computed as cos(pi * w/z).

Also, there are algebraic simplifications possible.  If z is an
integer greater than 4, and not a prime number, then the value
of your expression is always going to be 1.  If z is a prime
number then Wilson's theorem is going to come in handy.
(Google "Wilson's theorem prime").

Where does the expression come from?  Is z a real or an integer?
Is this a genuine real-world formula, or something that appeared
in an elementary number theory textbook?


More information about the Python-list mailing list