GATE / CS ARCHIVE

GATE CSE 2007 / QUESTION 45

Recursion repeatedly taking the square root

Algorithms · Asymptotic Analysis & Recurrences · Full GATE CSE 2007 paper

GATE 2007, Q45 2 marks · MCQ
Report issue

Asymptotic Analysis & Recurrences

Question 45, GATE 2007: What is the time complexity of this recursive function, with unit-cost arithmetic and square root?
int DoSomething(int n) {
    if(n<=2) return 1;
    else return DoSomething(floor(sqrt(n))) + n;
}
Options:
(A) Θ(n²)
(B) Θ(n log₂ n)
(C) Θ(log₂ n)
(D) Θ(log₂ log₂ n)
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Approach. The function makes one recursive call, not n calls. Each square root halves the logarithm of the argument, so analyze the recursion in terms of log n.

2. Derivation and interpretation. Assuming unit-cost integer arithmetic and square root as intended, T(n)=T(floor(sqrt(n)))+Θ(1). After k reductions the argument is approximately n1/2^k, and reaches a constant when 2k=Θ(log n). Thus k=Θ(log log n), giving D. Adding n to the returned value is one arithmetic operation, not n operations; floors change only constant-level stopping details.

Original paper, page 10