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 Answer 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)
.
-
Thats What i though.. but wasn't sure about.. Thanks :)geekybedouin– geekybedouin03/03/2013 11:19:47Commented Mar 3, 2013 at 11:19
-
1If
n=2^64
=>O(lgn) = 64
; however loop executes only 6 times.जलजनक– जलजनक03/03/2013 11:37:35Commented Mar 3, 2013 at 11:37 -
@icepack so its log^2 or log(logn)?? the second one ryt??geekybedouin– geekybedouin03/03/2013 12:49:03Commented Mar 3, 2013 at 12:49
-
Yes (it would've been
logn
if power ofi
in each iteration was multiplied by constant)SomeWittyUsername– SomeWittyUsername03/03/2013 12:53:17Commented Mar 3, 2013 at 12:53
Explore related questions
See similar questions with these tags.