Skip to content
Official PYQ · 2007

GATE CS 2007 Q45 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

What is the time complexity\text{time complexity} of the following recursive function?

int  DoSomething (int n) {
    if (n <= 2)
        return 1;
    else 
        return (DoSomething (floor (sqrt(n))) + n);
}
Choose one option
View worked solution

Answer: D

To find the time complexity of the recursive function, let us write its recurrence relation. Let T(n)T(n) represent the number of steps (or time complexity) taken by DoSomething(n).

For n>2n > 2, the function makes one recursive call with the argument ⌊n⌋\lfloor\sqrt{n}\rfloor and performs a constant amount of work, Θ(1)\Theta(1), for the addition and comparison operations.

Thus, the recurrence relation is: T(n)=T(n)+Θ(1)T(n) = T(\sqrt{n}) + \Theta(1) with the base case T(n)=Θ(1)T(n) = \Theta(1) for n≤2n \le 2.

We can solve this recurrence using the change of variables method:

  1. Let n=2mn = 2^m, which implies m=log⁡2nm = \log_2 n.
  2. Substituting this into the recurrence: T(2m)=T(2m/2)+Θ(1)T(2^m) = T\left(2^{m/2}\right) + \Theta(1)
  3. Let S(m)=T(2m)S(m) = T(2^m). The recurrence becomes: S(m)=S(m2)+Θ(1)S(m) = S\left(\frac{m}{2}\right) + \Theta(1)

Applying Case 2 of the Master's Theorem to S(m)S(m): S(m)=Θ(log⁡2m)S(m) = \Theta(\log_2 m)

Substituting back m=log⁡2nm = \log_2 n, we get: T(n)=Θ(log⁡2log⁡2n)T(n) = \Theta(\log_2 \log_2 n)

Therefore, the time complexity of the function is Θ(log⁡2log⁡2n)\Theta(\log_2 \log_2 n).

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions