If I have
int i;
for(i = 1; i < n; i *= 2) //n is the size of an array passed to the function
{
//O(1) code here
}
What is the Big O complexity? The "i *= 2" bit is confusing me. I tried operation counting but now I'm even more confused.
If I have
int i;
for(i = 1; i < n; i *= 2) //n is the size of an array passed to the function
{
//O(1) code here
}
What is the Big O complexity? The "i *= 2" bit is confusing me. I tried operation counting but now I'm even more confused.
It looks like O(log(n)), because you iterate not over the whole sequence, but use power-of-two steps.
complexity is O(log2(N))
Basically your 'i' doubles every iteration so after 1 iteration it's 2, then 4, then 8. so if n = 28 then the loop will iterate (roughly) 8 times.
You'd be halving the steps each time, so you'd end up with O(log n), where n is the total number of iterations. See this: What would cause an algorithm to have O(log n) complexity?
The complexity is O(log n)
.
You can rewrite the loop to
for(x = 0; pow(2,x) < n; x++)
so x < log n
. (pow
should compute 2x
)