Assume $n=2^k$, write an algorithm that can find $k$.
**log function is not allowed.
Is there an efficient way to find the power instead of multiplying by 2 until it equals $n$? What is the optimal efficiency?
Computer Science Stack Exchange is a question and answer site for students, researchers and practitioners of computer science. It only takes a minute to sign up.
Sign up to join this communityAssume $n=2^k$, write an algorithm that can find $k$.
**log function is not allowed.
Is there an efficient way to find the power instead of multiplying by 2 until it equals $n$? What is the optimal efficiency?
Assuming arithmetic operations take constant time, you can compute it in $O(\log \log n)$ time.
Start with $n_0=2$ and iteratively compute $n_i = n_{i-1} \cdot n_{i-1} = 2^{2^i}$ until $n_{i} > n$.
The number of iterations is then $\log \log n$ and $ n_{i-1} = 2^{2^{i-1}} \le n < 2^{2^i} = n_i$. At this point you can binary search for the right exponent among the $2^i - 2^{i-1} = 2^{i-1} \le k$ possible exponents. This takes time $O(\log k) = O(\log \log n)$ (exponentiation with a base of $2$ can usually be performed with a single left shift operation).