0

What's the time complexity of this loop?

j=2
while(j <= n)
{
 //body of the loop is Θ(1)
 j=j^2
}
irrelephant
4,1092 gold badges27 silver badges41 bronze badges
asked Aug 1, 2012 at 6:43

1 Answer 1

3

You have

j = 2

and each loop : j = j^2

The pattern is :

2 = 2^(2^0)
2*2 = 2^(2^1)
4*4 = 2^(2^2)
16*16 = 2^(2^3)

Which can be seen as :

2^(2^k) with k being the number of iteration

Hence loop stops when :

2^(2^k) >= n
log2(2^(2^k)) >= log2(n)
2^k >= log2(n)
log2(2^k) >= log2(n)
k >= log2(log2(n))

the complexity is log2(log2(n))

answered Aug 1, 2012 at 6:51
2
  • can you explain why it would be Log2(n)? Commented Aug 1, 2012 at 7:28
  • 1
    Yes sorry, i was on my mobile phone and planned to explain more when in front of a computer. And the answer was wrong on top of that ... Commented Aug 1, 2012 at 7:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.