[英]How to decrease the time complexity of the following python code?
看起來當前的內存復雜度是 O(1),時間復雜度是 O(k)。 如何將內存復雜度保持在 O(1) 但將時間復雜度降低到 O(log k)?
import math
# for loop includes k/2 (ie. if k/2 = 3.5, then i will go from [1, 3]. 1,2, and 3
def findPower(x,k):
y =1
m = math.trunc(k/2)
if k == 0:
return 1
for i in range(1,m+1):
y = y * x
if(k%2 == 0):
return y * y
else:
return y*y*x
您想要fast power algorithm ,但您可能需要一個循環來正確實現它(而不是簡單的if
s):
def fast_power(e, p):
current = e
result = 1
while p > 0:
if p % 2 == 1:
result *= current
p = p // 2
current *= current
return result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.