简体   繁体   English

渐近时间复杂度 O(sqrt(n)log(n)n)

[英]Asymptotic time complexity O(sqrt(n)log(n)n)

for(int i=1; i*i <= n; i = i+1) {
   for(int j = n; j >= 1; j/4)   {
      for(int k = 1; k <= j; k=k+1) {
         f();
      }
   }
}

Why is the asymptotic complexity of this function O(n^{3/2}) ?为什么这个函数的渐近复杂度是O(n^{3/2}) I think, it should be O(sqrt(n)log(n)n) .我认为,它应该是O(sqrt(n)log(n)n) Is this the same to O(sqrt(n)n) ?这与O(sqrt(n)n)吗? Then, it would be O(n^{3/2}) ..然后,它将是O(n^{3/2}) ..

  • Outer loop is O(sqrt(n)) .外循环是O(sqrt(n))
  • first inner loop is O(log(n)) .第一个内部循环是O(log(n))
  • second inner loop is O(n) .第二个内循环是O(n)

The outer two loops (over i and j ) have bounds that depend on n , but the inner loop (over k ) is bounded by j , not n .外部的两个循环(在ij )的边界取决于n ,但内部循环(在k )受j限制,而不是n

Note that the inner loop iterates j times;请注意,内部循环迭代了j次; assuming f() is O(1) , the cost of the inner loop is O(j) .假设f()O(1) ,内部循环的成本是O(j)

Although the middle loop (over j ) iterates O(log n) times, the actual value of j is a geometric series starting with n .尽管中间循环(在j )迭代了O(log n)次,但j的实际值是一个以n开头的几何级数 Because this geometric series ( n + n/4 + n/16 + ... ) sums to 4/3*n , the cost of the middle loop is O(n) .因为这个几何级数 ( n + n/4 + n/16 + ... ) 总和为4/3*n ,所以中间循环的成本是O(n)

Since the outer loop iterates sqrt(n) times, this makes the total cost O(n^(3/2))由于外循环迭代sqrt(n)次,这使得总成本O(n^(3/2))

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

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