While loop Time complexity

本小妞迷上赌 提交于 2019-12-12 01:29:51

问题


I have an algorithm exam.. and am a bit not great in the loops time complexity :s I just started to get the basics of it..

I have this while loop

i=2
while (i<n)
{
   i=i*i
   x=x+1
}

I believe that the solution must be like:
(i) will run from 2 to 2k where k = 2i
every time it execute the statement 1 time..

so 1+1+1+.. , this means 1*2k

and from here I can't continue..

the second question guys.. please recommend a site or sth that I can practice some more of these.. searched but didn't find :s


回答1:


The loop runs as long as the i is less than n. In other words, you need to find k such that 22k < n. ==> k = log2log2n. So the loop iterates for log2log2n times and at each iteration it performs 2 operations (multiplication and addition) - these operations take O(1) time.

==> The time to execute the loop is equal to log2log2n * O(1) ==> total complexity is O(loglogn).



来源:https://stackoverflow.com/questions/15184862/while-loop-time-complexity

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