Worst case time complexity analysis pseudocode

淺唱寂寞╮ 提交于 2019-12-02 14:59:27

问题


Could someone help me out with the time complexity analysis on this pseudocode? I'm looking for the worst-case complexity here, and I can't figure out if it's O(n^4), O(n^5) or something else entirely. If you could go into detail into how you solved it exactly, it would be much appreciated.

sum = 0
for i = 1 to n do
   for j = 1 to i*i do
       if j mod i == 0 then
          for k = 1 to j do
              sum = sum + 1

回答1:


First loop: O(n)

Second loop: i is in average n/2, you could have an exact formula but it's O(n²)

Third loop happens i times inside the second loop, so an average of n/2 times. And it's O(n²) as well, estimating it.

So it's O(n*n²*(1 + 1/n*n²)), I'd say O(n^4). The 1/n comes from the fact that the third loop happens roughly 1/n times inside the second one.

It's all a ballpark estimation, with no rigorous proof, but it should be right. You could confirm it by running code yourself.



来源:https://stackoverflow.com/questions/29720755/worst-case-time-complexity-analysis-pseudocode

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