【发布时间】:2015-03-01 15:02:51
【问题描述】:
我遇到了一个问题,我必须首先找到一个数字的阶乘,然后返回在阶乘中获得的位数。 我编写了程序,它运行良好。但时间是 5.0015 秒,我必须在 1 秒内完成。如何减少这种情况?
下面是我的程序:
def factorial(n):
fact = 1
for y in xrange(1,n+1):
fact = fact * y
return fact
t = int(raw_input())
raw_input()
for x in xrange(t):
n = int(raw_input())
print len(str(factorial(n)))
【问题讨论】:
-
它不会改变时间复杂度,但使用内置函数会更简单,可能更快:
len(str(math.factorial(n)))。 -
我已经试过了。但我必须降低时间复杂度
-
首先你的代码不是很清楚。如果您不使用它,为什么要定义
length?你为什么要循环而不是只做print len(str(factorial(n)))? -
@HerrActress,这很可能是一个在线代码问题,您必须使用 raw_input 来接收参数
-
即使是 memozation 也不会让您获得更好的复杂性(但它可以提高速度)。对于这个问题有一个有趣的看法,你可以查看这个问题:stackoverflow.com/questions/9815252/…
标签: python python-2.7