How to find a upper and lower bound of code?

☆樱花仙子☆ 提交于 2019-12-13 04:34:27

问题


I have some code and the text is

For following code, find a lower and upper bound if data for function f,g is given, and we know that is best and worst case is given, condition is fulfilled in most cases.

f:O(log(n)), and lower bound is 1

g:O(n) and lower bound is (logn)^2

I think that first line of my code is logn, then since n>log(n) I think that second line is O(n*log(n))and the last lines is nlogn I think because if I use summarization I get logn(n+(logn)^2-1) end then the O is O(n^2(logn)^2). And for lower bound is n(logn)^3 i am beginner in this so please tell me where I make a mistake. Thank you

for(int i=n;i>0;i/=2)
if(f()<=g())
for(int j=f()*f();j<n;j++)
f()

回答1:


Your code is badly formatted so it is not really clear what the code flow is. Assuming your code is actually equivalent to:

for(int i=n; i>0; i/=2) {
  if(f()<=g()) {
    for(int j=f()*f(); j<n; j++) {
      f();
    }
   }
}

You need to find the best and the worst case performance.

IMHO it is easier to go from inside to the outside (at least until you get more experience):

  1. The inner-most call f() is O(log(n)) in the worst case and O(1) in the best case.

  2. Since f()*f() is a constant the inner loop is O(n) times the previous step (which is f()) + 2 times f() for the initial value of j + there are also O(n) condition checks and O(n) increments which together can be expressed as a single O(n). So for the worst case it is O(n*log(n) + 2*log(n) + n) which is O(n*log(n)) and for the best case it is O(n*1 + 2 + n) which is O(n)

  3. The if itself is just time of the calculation of f() and g(). Since the condition is mostly true, we just add the cost of the inner loop. So for the worst case it is O(log(n) + n + n*log(n)) which is O(n*log(n)) and for the best case it is O(1 + log^2(n) + n) which is O(n) (O(n) dominates O(log^2(n)))

  4. The outer loop as you correctly noticed is always O(log(n)) times. So the total complexity is O(log(n)) times of the body (+ not forget about the check and increment, this might make a difference if the condition is mostly false). So the worst case is O(log(n)*n*log(n)+log(n)) which is O(n*log^2(n)) and the best case is O(log(n)*n + log(n)) which is O(n*log(n)).

Hopefully I didn't mess up with details. But the most important thing is to understand when to add an when to multiply; and to understand which part dominates the others when you simplify.



来源:https://stackoverflow.com/questions/54162589/how-to-find-a-upper-and-lower-bound-of-code

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