0

What is the time complexity of

x = 1
while( x < SomeValue )
{
    x *= 2;
}

I believe it is O(N), as the loop will continue for a fixed number of iteration. Is my assumption correct?

2
  • I don't mind being wrong, but just that if I am wrong then what is the right answer. Commented Aug 10, 2016 at 21:39
  • If it's a fixed number of iterations, how many is it? Commented Aug 10, 2016 at 22:08

2 Answers 2

3

The time complexity would be O(log(n)) because x is increasing exponentially.

Sign up to request clarification or add additional context in comments.

3 Comments

Unless SomeValue <= 1, in which case complexity is O(1).
@cybersam You could apply that argument to any big O notation. If you specify the value of n, you can always solve it to a constant, thereby turning it into O(1).
If SomeValue > 1, then the complexity is O(log(SomeValue)), not O(1).
1

The loop will execute in O(log n) time. Hopefully the math makes the reasoning more clear. Each iteration is constant time. To find the number of iterations relative to SomeValue, which we'll call t, you can see that after the nth iteration, x will have the value 2. The loop ends once xt. So to find the number of iterations needed to meet or exceed t, plug in 2 for x and solve for t. You get t=log₂(n). Hence, O(log n) time.

Comments

Your Answer

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.