简体   繁体   中英

Time complexity of a recursive algorithm with nested iterative function?

a)

void f(n){
  if(n<=1) return;
    else{
      g(n); //g(n) is O(N^2).
      f(n/2);
      f(n/2);
    } 
}

b)

void f(n){
  if(n<=1) return;
    else{
      g(n); //g(n) is O(N).
      f(n-1);
      f(n-1);
    } 
}

c)

void f(n){
  if(n<=1) return;
    else{
      g(n); //g(n) is O(N^2).
      f(n-1);
      f(n-1);
    } 
}

How do I count the O(n) complexity of the above two code snippet?

a) I got the answer O(n^2), because each f(n) calls itself twice recursively. And since the depth of the tree is LogN (n/2), the overall complexity is O(n^2), do i disregard the g(n) method since it is N^2 as well?

b) Since the depth of the tree is N, and each f(n) calls itself twice recursively. And since each level needs to perform g(n) operation N times, I got the answer O(N.2^(N)).

c) Same as b) but g(n) is performed N^2 time - hence O(N^2.2^(N)).

Is this correct?

a) The recursive equation is as bellow.

If you expand the recursion we have:

So we want to calculate last equation which is equal to:

Since the last part of above equation is a geometric serie we have:

So the recursion is .

b) The approach is same as before.

which is equal to:

So the answer is

c) Third part can solve with the same technique.

PS: Thanks to Alexandre Dupriez for his comment.

PS: For an elegant simplification of the summation read Alexandre 's comments bellow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM