Calculating factorial using Stirling's approximation I've used Stirling's approximation to compute a factorial but I want to know if it is a cleaner and more concise way to solve this kind of problem.

Here is my code:

from numba import jit
from decimal import Decimal
from math import pi

getcontext().prec = 128

@jit
def stirling(n):
    return Decimal((2.0*n+1.0/3.0)*pi).sqrt()*Decimal(n**n)/Decimal(n).exp()

if __name__ == "__main__":
    print(stirling(255144))


Also , how can I get rid off decimal.Overflow error?
The biggest problem of your code (while being very short itself) is that hard to read and complicated formula. One way to improve readability of the formula is by using meaningful variables to name parts of the formula. This also makes it easier to find errors, because you can first look in what part of the formula the error occurs, and debug more easily.

Furthermore, adding spaces around operators inside the formula makes it more readable.

However, Python already has a solution for that in the standard library. Since your question implies that your goal is not to implement Stirling's approximation, but rather a pythonic solution, I suggest the following:

from math import factorial

print(factorial(1337))


This is probably the most pythonic way of doing it. Using math.factorial from the standard library, your code becomes more readable and you get around hard to find errors by avoiding complicated formulas.