Here's my approach to factorials:
def factorial(n):
'''Returns factorial of n'''
r = 1
for i in range(1, n + 1):
r *= i
return r
I think it's pretty straightforward, though I guess you could make something more efficient, because it takes ages for large numbers like 100000. My question is, is there? math.factorial() is no good either, it takes roughly the same amount of time.
Factorials get very large, so it is often better to deal with logarithms of the number.
Many languages have an lgamma library function which computes the natural logarithm of the factorial of n-1.
This means that you can compute the natural logarithm of factorial(n) via lgamma(n+1).
You can divide by log10 to turn this into a base 10 logarithm.
So if you just want the number of digits, then this Python code will give the answer immediately:
from math import *
print ceil(lgamma(100000+1)/log(10))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With