Writing factorials within python

I have a question about writing factorials within Python (3! → 3 factorial = 3 * 2 * 1 = 6)

How would I write a factorial expression in Python?
Does it utilize the “!” symbol? If so, how would I ensure that Python doesn’t confuse a factorial number with the != comparator used to say that two statements are different?

Thank you!

The math library has a factorial method, that’ll cover you for natural numbers (including 0).
If you need special applications (non-natural numbers) you probably want to look into the gamma method or something like that.

To use it just import the library, and call the method!

import math


The run-time complexity for the function is O(n) in theory, but we quickly run into two issues, space, and the run-time of multiplying very large numbers. So even though the library is written in C, you may have some issues depending on how large an input you are giving it.

In fact, some fiddling will let you know the hard bounds to this library function is the 64-bit limit

OverflowError: factorial() argument should not exceed 9223372036854775807

so try calling the function on 9223372036854775807 and see how long it takes (I just spun it up for curiosity’s sake).

Additionally, this does not mean that you cannot do larger inputs over 64-bits, you probably just either need to look into other libraries or cook up your own factorial function that handles those scenarios.

1 Like