Skip to content
Official PYQ · 2015

GATE CS 2015 Set 3 Q39 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Consider the following recursive C function.

void get(int n)
{
    if (n<1) return;
    get (n-1);
    get (n-3);
    printf("%d", n);
}

If get(6)get(6) function is being called in main()main() then how many times will the get()get() function be invoked before returning to the main()main()?

Choose one option
View worked solution

Answer: B

To find the total number of times the function get() is invoked, we can define a recurrence relation. Let T(n)T(n) denote the total number of times get() is called (including the initial call) for an input nn.

1. Base Cases

When n<1n < 1, the condition if (n < 1) is satisfied, and the function returns immediately. This still counts as 11 invocation.

  • T(0)=1T(0) = 1
  • T(−1)=1T(-1) = 1
  • T(−2)=1T(-2) = 1

2. Recurrence Relation

For n≥1n \ge 1, the function is invoked once, and then it recursively calls get(n-1) and get(n-3). Therefore, the recurrence relation is:

T(n)=1+T(n−1)+T(n−3)T(n) = 1 + T(n-1) + T(n-3)

3. Step-by-Step Computation

Using the recurrence relation, we compute T(n)T(n) for n=1n = 1 to 66:

  • For n=1n = 1:
    T(1)=1+T(0)+T(−2)=1+1+1=3T(1) = 1 + T(0) + T(-2) = 1 + 1 + 1 = 3
  • For n=2n = 2:
    T(2)=1+T(1)+T(−1)=1+3+1=5T(2) = 1 + T(1) + T(-1) = 1 + 3 + 1 = 5
  • For n=3n = 3:
    T(3)=1+T(2)+T(0)=1+5+1=7T(3) = 1 + T(2) + T(0) = 1 + 5 + 1 = 7
  • For n=4n = 4:
    T(4)=1+T(3)+T(1)=1+7+3=11T(4) = 1 + T(3) + T(1) = 1 + 7 + 3 = 11
  • For n=5n = 5:
    T(5)=1+T(4)+T(2)=1+11+5=17T(5) = 1 + T(4) + T(2) = 1 + 11 + 5 = 17
  • For n=6n = 6:
    T(6)=1+T(5)+T(3)=1+17+7=25T(6) = 1 + T(5) + T(3) = 1 + 17 + 7 = 25

Thus, the get() function is invoked a total of 2525 times before returning to main().

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

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