如何减少以下python代码的时间复杂度?

时间:2018-09-19 02:30:14

标签: python time-complexity big-o

看起来当前的内存复杂度为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

1 个答案:

答案 0 :(得分:1)

您想要fast power algorithm,但是您可能需要一个循环来正确实现它(而不是普通的if):

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