Python里的math.pow()函数虽然效率很快,但是无法求大指数
Traceback (most recent call last):
File "阅读笔记/算法/test.py", line 409, in <module>
num = math.pow(1048,12343)
OverflowError: math range error
但是求大指数的效率又是很重要的问题
先看看O(n^2)的递归算法:
def n2Power(x,n):
index = n
rs =1
while index>0:
rs*=x
index-=1
return rs
看一下效率:
s = time.clock()
num = n2Power(1048,12343)
e = time.clock()
time= e-s
print time
:!python 阅读笔记/算法/test.py
0.030409
使用分治思想的O(lgn)算法:
def lgnPower(x,n):
if n <= 1:
return x
#区分奇偶
if n%2==0:
return lgnPower(x,n/2)*lgnPower(x,n/2)
else:
return lgnPower(x,(n-1)/2)*lgnPower(x,(n-1)/2)*x
结果:
:!python 阅读笔记/算法/test.py
0.006834
具体数值就不贴出来了,找出屏幕了