繁体   English   中英

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

[英]Time Complexity of Nested For Loop with If

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)

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

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

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

在此输入图像描述

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

更多详情请访问: https//math.stackexchange.com/questions/1840414/summation-with-floor-and-square-root-functions-tight-bounds

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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