The problem asks for the complexity of computing the cube root of n, where n is represented in binary. This means the size of the input is not the value n, but the number of bits required to represent n, which is b=Θ(logn).
The most efficient algorithm for this is to use binary search.
The Algorithm: We are looking for the largest integer m such that m3≤n. We can binary search for this value m in the range [1,n].
Number of Iterations: A binary search on a range of size n takes O(logn) iterations.
Cost of Each Iteration: In each iteration, we take a midpoint mid and compute mid³.
The numbers we are dealing with (like mid) can have up to Θ(logn) bits.
The cost of multiplying two b-bit numbers is, at worst, O(b2). So, computing mid³ takes O((logn)2) time.
Total Time Complexity:
Total Time=(Number of Iterations)×(Cost per Iteration)
Total Time=O(logn)×O((logn)2)=O((logn)3)
Evaluating the Options
Our calculated complexity is O((logn)3). Let's see which option this fits.
A. O(n)...: False. O((logn)3) is much smaller than O(n).
B. O(n0.5)...: False. O((logn)3) is much smaller than O(n0.5).
C. O((logn)k) for some constant k>0, but not O((loglogn)m) for any constant m>0:
Is our complexity O((logn)k)? Yes, for k=3.
Is it "not O((loglogn)m)"? Yes, because (logn)3 grows faster than any power of loglogn.
This statement is true.
D. O((loglogn)k)...: False.
This confirms that C is the correct answer. The key is to analyze the complexity in terms of the number of bits, which leads to a polylogarithmic time complexity.
Let's run the algorithm on two examples: a non-perfect cube (
) and a perfect cube (
).
The goal is to find the largest integer m such that
.
Example 1: n = 30
Initial state: low = 1, high = 30, answer = 0
| Iteration | low | high | mid | mid³ | Condition mid³ <= 30? | Action | answer |
| 1 | 1 | 30 | 15 | 3375 | False | high = 14 | 0 |
| 2 | 1 | 14 | 7 | 343 | False | high = 6 | 0 |
| 3 | 1 | 6 | 3 | 27 | True | answer = 3, low = 4 | 3 |
| 4 | 4 | 6 | 5 | 125 | False | high = 4 | 3 |
| 5 | 4 | 4 | 4 | 64 | False | high = 3 | 3 |
At this point, low is 4 and high is 3. The condition low <= high is false, so the loop terminates.
The final answer is the last stored value in answer, which is 3. This is correct, as 3^3=27≤30 and 4^3=64>30.
Example 2: n = 27
Initial state: low = 1, high = 27, answer = 0
| Iteration | low | high | mid | mid³ | Condition mid³ <= 27? | Action | answer |
| 1 | 1 | 27 | 14 | 2744 | False | high = 13 | 0 |
| 2 | 1 | 13 | 7 | 343 | False | high = 6 | 0 |
| 3 | 1 | 6 | 3 | 27 | True | answer = 3, low = 4 | 3 |
| 4 | 4 | 6 | 5 | 125 | False | high = 4 | 3 |
| 5 | 4 | 4 | 4 | 64 | False | high = 3 | 3 |
Again, the loop terminates because low (4) becomes greater than high (3).
The final answer is 3, which is the correct integer cube root of 27.