I have been learning DSA, but calculating time complexity is a little difficult
I understand the logic of O(n^2) or O(n)
but what will be the time complexity of and how?:
while(n%2 == 0) {
n/=2;
}
It will be O(n/2)? not sure
There's obviously a lower bound of O(1)
for when n
is initially odd. But that's not the complete answer.
There is an upper bound.
Here's a hint. How many loop iterations of executing n = n/2
for the following initial values of n
:
n = 1 => 0 iteration
n = 2 => 1 iterations
n = 4 => ?
n = 8 => ?
n = 16 => ?
n = 32 => ?
n = 64 => ?
n = 128 => ?
Now what math function, can f(n)
be implemented with that can predict the count of iterations given an initial value of n
? This will give you an upper bound for the runtime complexity.
You can test it practically to see how much iterations loop will have depending of n
int main()
{
int n = 2048;
int count = 0;
while(n%2 == 0) {
n/=2;
++count;
}
std::cout << count;
return 0;
}
So, when n = 1024, count = 10 when n = 2048, count = 11
2^(iteration count) = N;
So, complexity would be O(Log 2 (N))
To evaluate the time complexity of your code, always test for the worst case possible.
For instance, if you try n = 9 , the while
won't even enter. So the worst case possible is when you divide n more times, and that case would be n = 2 k .
Now, it's easy to see that you need k operations for the while
to finish.
If n = 2 k , then k = log 2 (n) , hence the complexity is O(log 2 (n)) .
To evaluate complexity we must test the worst possible case.
If we write a recurrence relation or the recursive version for your loop, it will look somewhat like
T(n)=T(n/2)
If we iterate this manually for a few iterations it will look like
T(n/2)=T(n/4)
T(n/4)=T(n/8)
...
... and so on
So the general case for T(n) will be
T(n)=T(n/2 k ) We know that T(1)=1 since it is constant and to convert n/2 k into T(1), we put n = 2 k
Which is gives us the time complexity of your loop which is
O(log 2 (n))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.