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?
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?
The time complexity would be O(log(n)) because x is increasing exponentially.
SomeValue <= 1, in which case complexity is O(1).n, you can always solve it to a constant, thereby turning it into O(1).O(log(SomeValue)), not O(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 x≥t. 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.