Time Complexity of this double loop

我与影子孤独终老i 提交于 2020-12-13 04:09:45

问题


What will be the time complexity of this code?

 for(int i = 1 ; i <= b ; ++i )
     for(int j = i ; j <= b ; j += i )

回答1:


You can expand the loops to something like this:

i = 1 ——>   1,2,3,…,b     b
i = 2 ——>   1,3,5,…,b     (b/2)
i = 3 ——>   1,4,7,…,b     (b/3)
i = 4 ——>   1,5,9,…,b     (b/4)
  …
i = b ——>   1, b          (b/b = 1)

This expands into a sum of the form:

b + b/2 + b/3 + … + b/b = b * (1 + 1/2 + 1/3 + … + 1/b)

You might recognize the second factor as the Harmonic Series. Then, using the result from the following SO answer: Finding Big O of the Harmonic Series you can get the Big Oh of your nested loops:

O(b * log(b))


来源:https://stackoverflow.com/questions/40332225/time-complexity-of-this-double-loop

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