Time Complexity of Nested For Loop with If

旧街凉风 提交于 2019-12-10 20:05:08

问题


void f(int n)
{
  for(int i =1; i<=n; i++){
    if(i % (int)sqrt(n)==0){
      for(int k=0; k< pow(i,3); k++){
        //do something
      }
    }
  }
}

My thinking process: number of times execute if statement: sum i=1 to n (theta(1)).

number of times execute things inside if: sum i=1 to sqrt(n) (for loop)

number of times execute for loops: sum k=0 to i^3 (theta(1)) = i^3

This will give me: theta(n) + sum i=0 to sqrt(n) (theta(i^3)) = theta(n) + theta(n^2)

which gives me theta(n^2)

The answer key he gave is theta(n^3.5)

I am just wondering if i made any mistake on my thinking process. I have asked my professor twice about this question. Just want to see if there is anything I didn't see before I bother him again.. Thanks!


回答1:


Using Sigma notation, I came up with the exact closed-form.

Besides, the formula below assumes the process, which doesn't verify the condition that executes the innermost loop, is negligible.

It's up to you to determine tight order of growth bounds, because of flooring function and square root etc.

Further details here: https://math.stackexchange.com/questions/1840414/summation-with-floor-and-square-root-functions-tight-bounds




回答2:


void f(int n) {   
  for(int i =1; i<=n; i++){     //---   n times
    if(i % (int)sqrt(n)==0){    // ---  2 times (constant)
      for(int k=0; k< pow(i,3); k++){  // sqrt(n)^3 and n^3 times
        //do something
      }
    }   
  } 
}

Taking the highest order term it should be Theta(n^3)

Assuming do something is constant

c = do somrthing + plus running cost of single iteration of inner loop

a = runnning cost of running single iteration of outer most loop

b = running cost of if block Thinking more about it cn^3/2 + cn^3 + a*n + b*2)

Taking the highest order term Theta(n^3) or since c is same coefficient for both the n^3 and n^3/2 we can reduce it

= cn^3 + cn^3/2

= cn^3(n^1/2+1)

~ cn^3 * n^1/2

= cn^3.5



来源:https://stackoverflow.com/questions/37982893/time-complexity-of-nested-for-loop-with-if

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