Asymptotic Complexity for an Algorithm

对着背影说爱祢 提交于 2019-12-14 03:29:42

问题


i <-- 0
while(i < n)  
    someWork(...)
    i <-- i^2
done

Can someone confirm that the worst case time complexity (Big-O) of this loop is O(log n) if:

  1. someWork(...) is an O(1) algorithm

  2. someWork(...) is an O(n) algorithm

Also, what is the worst case time complexity (Big-O) if someWork(...) does exactly i operations? someWork(...) does more work as i increases. Your answer should be something like sigma(f(i)).

Thank you very much for any help.


回答1:


First: if (as mentioned) 0 <= i <= 1 holds, the algorithm will never terminate.

So: Let i > 1.

In every round of the loop the exponent of i will be doubled. So in the k-th round the number will be i^(2^k). The loop keeps going as long as i^(2^k) < n holds, which is equivalent to k < log log n. Exactly it is log_2 log_i n, but due to all logarthms are equal exept for a constant factor, I just write log log n. Notice: if i is not constant, 1/log log i has to be multiplied to the complexity.

So the complexity of the algorithm is

  1. O(log log n), if someWork() is in O(1)
  2. O(n log log n), if someWork() is in O(n)

If someWork() does O(i^(2^k)) operations in round k you get a total complexity of

O( i + i^2 + i^(2^2) + i^(2^3) + ... + i^(2^(log log n)) ) 

This simplifys to O(i * i^(2^(log log n)) ) = O(i * n) or O(n) if i is constant.

To see the simplification take a look at the following:
The number i + i^2 + i^4 + i^8 can be written in i-ary as 100 010 110. So you can see that

i + i^(2^1) + i^(2^2) + ... + i^(2^k) < i * i^(2^k)

holds, since it is equal to 100 010 110 < 1 000 000 000.

Edit:
I'm not sure what you mean by sigma notation but maybe it is this:



来源:https://stackoverflow.com/questions/24581182/asymptotic-complexity-for-an-algorithm

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