具有If的嵌套for循环的时间复杂度

时间:2016-06-23 05:17:24

标签: c++ loops runtime time-complexity big-o

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
      }
    }
  }
}

我的思考过程: 执行if语句的次数:sum i = 1到n(theta(1))。

执行内部操作的次数if:sum i = 1 to sqrt(n)(for loop)

执行循环的次数:sum k = 0到i ^ 3(theta(1))= i ^ 3

这将给我:theta(n)+ sum i = 0到sqrt(n)(theta(i ^ 3))= theta(n)+ theta(n ^ 2)

给了我theta(n ^ 2)

他给出的答案钥匙是theta(n ^ 3.5)

我只是想知道我的思维过程是否犯了错误。我曾两次问我的教授这个问题。只是想看看在我再次打扰他之前是否还有什么我看不到的东西..谢谢!

2 个答案:

答案 0 :(得分:1)

使用Sigma表示法,我想出了确切的封闭形式。

此外,下面的公式假设该过程不能验证执行最内层循环的条件,可以忽略不计。

enter image description here

由于地板功能和平方根等原因,您需要确定增长界限的紧密程度。

此处有更多详情:https://math.stackexchange.com/questions/1840414/summation-with-floor-and-square-root-functions-tight-bounds

答案 1 :(得分:0)

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
      }
    }   
  } 
}
  

取最高阶项,应该是Theta(n ^ 3)

     

假设做某事是不变的

     

c =做somrthing +加上内部单次迭代的运行成本   环

     

a =运行最外层循环的单次迭代的运行成本

     

b = if块的运行成本更多关于它的思考c n ^ 3/2 + c n ^ 3   + a * n + b * 2)

     

采用最高阶词Theta(n ^ 3)或   由于c对于n ^ 3和n ^ 3/2都是相同的系数,我们可以减少   它

     

= cn ^ 3 + cn ^ 3/2

     

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

     

~cn ^ 3 * n ^ 1/2

     

= cn ^ 3.5