ProgrammingModerateTCS NQT · Accenture
What is the time complexity of the following pseudocode, as a function of n?
What is the time complexity of the following pseudocode, as a function of n?
Function f(Integer n)
if (n <= 1)
return 1
end if
return f(n - 1) + f(n - 1)
End Function- A. O(2ⁿ)
- B. O(n)
- C. O(n²)
- D. O(n log n)
Correct answer: A. O(2ⁿ)
Each call makes two calls on n − 1, so the call tree doubles at every level: 1 + 2 + 4 + … + 2ⁿ⁻¹ calls, i.e. O(2ⁿ). Writing 2 * f(n − 1) instead would make it O(n).
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (OR stops evaluating once the left side is true; ++c adds 1 to c and then gives the…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer nxt[8] = {1, 2, 3, 4, 5, 6, 7, 3} Integer slow =…
- What will be the output of the following pseudocode? (mod is applied to (i j) before adding) Integer x = 0 for (each i from 1 to 5) for…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer A[2][3] = {{1, 2, 3}, {4, 5, 6}} Integer Bm[3][2]…
- What will be the output of the following pseudocode? Function J(Integer n, Integer k) if (n == 1) return 0 end if return (J(n - 1, k) + k)…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Function gcd(Integer a…