k = n; //integer division
while(k > 1) {
std::cout << k;
k=k/2;
}
I need to find out the asymptotic estimate as a function of n.
k = n; //integer division
while(k > 1) {
std::cout << k;
k=k/2;
}
I need to find out the asymptotic estimate as a function of n.
The complexity is logarithmic.
Assuming K is non-negative, division by two is equivalent to shifting right by one bit. Therefore, the maximum number of iterations before k
becomes 0 is the number of bits in k
. More specifically, the position of the most significant bit in k
that is set (i.e., a 1
) will determine the number of iterations executed in the loop.
Since the operations in the loop are (presumably) constant complexity, logarithmic number of iterations leads directly to logarithmic complexity.