geekybedouin
geekybedouin

Reputation: 559

While loop Time complexity

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

Upvotes: 0

Views: 12300

Answers (1)

SomeWittyUsername
SomeWittyUsername

Reputation: 18348

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).

Upvotes: 2

Related Questions