Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

big o - Asymptotic Complexity for an Algorithm

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:
enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...