how can i figure the order of complexity?

允我心安 提交于 2019-12-12 02:33:36

问题


I think I know the complexity of these 2 codes but I simply cant find the right equations to prove it. The first one I assume is O(loglogn). The second one is O(n^2).

def f1(lst):
    i=2
    while i<len(lst):
        print(lst[i])
        i **= 2

the second code:

def f2(lst):
    i = len(lst)
    while i>0:
        for j in range(i):
            for k in range(10**5, j, -5):
                print(i)
        i -= 2

回答1:


I think you can try to get the recursive equation first, and then use master theorem or something else to solve the recursive equations. For the first one, we use the length of the lst as the parameter.

def f1(lst1): #len(lst2)=N
    i=2
    while i<len(lst1):
        print(lst1[i])
        i **= 2

def f1(lst2): #len(lst2)=N^2
    i=2
    while i<len(lst2):
        print(lst2[i])
        i **= 2

you will notice that the second one will execute only once more than the first one. so you get

T(N^2)=T(N)+1.

For simplification, just suppose N^2=2^k,

then T(2^k)=T(2^(k/2))+1,let f(k)=T(2^k),

then f(k)=f(k/2)+1,

with the master theorem, T(N^2) = f(k) = log(k) = log(log(2^k)) = log(log(N^2)).

we get T(N) = O(loglog(N)) at last.



来源:https://stackoverflow.com/questions/20425922/how-can-i-figure-the-order-of-complexity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!