Order Of Growth complicated for loops

折月煮酒 提交于 2019-12-01 11:53:20

You have a geometric progression in your outer loops, so there is a closed form for the sum of which you want to take the log:

1 + 2 + 4 + ... + 2^N = 2^(N+1) - 1

To be precise, your sum is

1 + ... + 2^(floor(ld(N))

with ld denoting the logarithm to base 2.

The outer two loops are independent from each other, while the innermost loop only depends on i. There is a single operation (increment) in the innermost loop, which means that the number of visits to the innermost loop equals the summation result.

  \sum_i=1..( floor(ld(N)) ) {
      \sum_j=1..( floor(ld(N)) ) {
          \sum_k=1..2^i { 1 }
      }
  }

    // adjust innermost summation bounds   
= \sum_i=1..( floor(ld(N)) ) {
      \sum_j=1..( floor(ld(N)) ) {
          -1 + \sum_k=0..2^i { 1 }
      }
  }

    // swap outer summations and resolve innermost summation
= \sum_j=1..( floor(ld(N)) ) {
      \sum_i=1..( floor(ld(N)) ) {
          2^i
      }
  }

   // resolve inner summation
= \sum_j=1..( floor(ld(N)) ) {
      2^(floor(ld(N)) + 1) - 2
  }

   // resolve outer summation
= ld(N) * N - 2 * floor(ld(N))

This amounts to O(N log N) ( the second term in the expression vanishes asymptotically wrt to the first ) in Big-Oh notation.

To my understanding, the outer loop will take log N steps, the next loop will also take log N steps, and the innermost loop will take at most N steps (although this is a very rough bound). In total, the loop has a runtime complexity of at most ((log N)^2)*N, which can probably be improved.

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