简体   繁体   中英

What is the space complexity of this algorithm (n or log(n))?

I have a question regarding the space (memory) complexity of this particular piece of pseudocode:

int b(int n, int x) {
   int sol = x;
   if (n>1) {
      for (int i = 1; i <= n; i++) {
         sol = sol+i;
      }
      for (int k=0; k<3; k++) {
         sol = sol + b(n/3,sol/9);
      }
   }
   return sol;
}

The code gets called: b(n,0)

My opinion is, that the space complexity progresses linearly, that is n , because as the input n grows, so does the amount of variable declarations ( sol ).

Whereas a friend of mine insists it must be log(n) . I didn't quite get his explanation. But he said something about the second for loop and that the three recursive calls happen in sequence.

So, is n or log(n) correct?

I think the complexity is

O(log 3 base (n) )

The total number times function b is called is O(n) , but space complexity is O(log(n)) .

Recursive calls in your program cause the execution stack to grow. Every time a recursive call takes place all local variables are pushed to the stack (stack size increases). And when function comes back from recursion the local variables are poped from the stack (stack size decreases).

So what you want to calculate here is the maximum size of execution stack, which is maximum depth of recursion, which is clearly O(log(n)) .

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