[英]Factorial Huge Number Python
I am trying to make a program that can compute the factorial of 987654321, but I can't find a way to do it. 我正在尝试制作一个可以计算987654321的阶乘的程序,但是我找不到解决方法。
def range_prod(lo,hi):
if lo+1 < hi:
mid = (hi+lo)//2
return range_prod(lo,mid) * range_prod(mid+1,hi)
if lo == hi:
return lo
return lo*hi
def treefactorial(n):
if n < 2:
return 1
return range_prod(1,n)
print(treefactorial(987654321))
The proposed approaches will take a very long time to compute. 所提出的方法将花费很长时间来计算。 If you're OK with losing some precision, you can get an approximate value quickly using the LogGamma function, for example
如果可以接受一些精度,可以使用LogGamma函数快速获得一个近似值,例如
math.exp(scipy.special.gammaln(3+1))
=> 6.0
scipy.special.gammaln(987654322)
=> 19467499583.824226
so 987654321!
所以
987654321!
is approximately exp(19467499583.824226)
you can convert to log 10
base to find the number of digits... 大约是
exp(19467499583.824226)
您可以转换为log 10
底数来找到位数...
ps. PS。 It will have more than 8 billion digits.
它将有超过80亿个数字。
You can use builtin math.factorial
您可以使用内置的
math.factorial
import math
math.factorial(n)
Or you can use reduce
function to calculate factorial 或者您可以使用
reduce
函数来计算阶乘
from operator import mul
for Python 2.7
对于Python 2.7
factorial = lambda n: reduce(mul, xrange(1, n+1))
for Python 3
对于Python 3
factorial = lambda n: reduce(mul, range(1, n+1))
>>> factorial(987654321)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.