What is the of the following recursive function?
int DoSomething (int n) {
if (n <= 2)
return 1;
else
return (DoSomething (floor (sqrt(n))) + n);
}
View worked solution
Answer: D
To find the time complexity of the recursive function, let us write its recurrence relation. Let represent the number of steps (or time complexity) taken by DoSomething(n).
For , the function makes one recursive call with the argument and performs a constant amount of work, , for the addition and comparison operations.
Thus, the recurrence relation is: with the base case for .
We can solve this recurrence using the change of variables method:
- Let , which implies .
- Substituting this into the recurrence:
- Let . The recurrence becomes:
Applying Case 2 of the Master's Theorem to :
Substituting back , we get:
Therefore, the time complexity of the function is .
Free practice · Your answers on this page are not saved.
