Skip to content
Official PYQ · 2020

GATE CS 2020 Q48 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Consider the following C functions.

int tob (int b, int* arr) {
    int i;
    for (i = 0; b>0; i++)  {
        if (b%2)  arr [i] = 1;
        else      arr[i] = 0;
        b = b/2;
    }
    return (i);
}

 

 

int pp(int a, int b)  {
    int  arr[20];
    int i, tot = 1, ex, len;
    ex = a;
    len = tob(b, arr);
    for (i=0; i<len ; i++) {
         if (arr[i] ==1)
             tot = tot * ex;
         ex= ex*ex;
    }
return (tot) ;
}

The value returned by pp(3,4)pp(3,4) is _______.

View worked solution

Answer: 81

The function pp(a, b) implements the standard binary exponentiation (or exponentiation by squaring) algorithm to compute aba^b. Let us trace the execution for pp(3, 4) step-by-step.

Step 1: Trace of tob(4, arr)

The function tob(b, arr) converts the integer bb into its binary representation and stores the bits in arr in least-significant-bit (LSB) first order. It returns the number of bits (length).

For b=4b = 4:

  • Iteration 1 (i=0i = 0): b=4b = 4. Since 4%2==04 \% 2 == 0, arr[0] = 0. Then b=4/2=2b = 4/2 = 2.
  • Iteration 2 (i=1i = 1): b=2b = 2. Since 2%2==02 \% 2 == 0, arr[1] = 0. Then b=2/2=1b = 2/2 = 1.
  • Iteration 3 (i=2i = 2): b=1b = 1. Since 1%2==11 \% 2 == 1, arr[2] = 1. Then b=1/2=0b = 1/2 = 0.

The loop terminates because b=0b = 0. The function returns i = 3. Thus, len = 3 and arr = {0, 0, 1}.

Step 2: Trace of pp(3, 4)

We initialize ex = a = 3, tot = 1, and len = 3. The loop runs for i=0,1,2i = 0, 1, 2:

Iteration (ii) arr[i] Condition arr[i] == 1 Value of tot Next Value of ex (ex * ex)
00 00 False 11 3×3=93 \times 3 = 9
11 00 False 11 9×9=819 \times 9 = 81
22 11 True 1×81=811 \times 81 = 81 81×81=656181 \times 81 = 6561

After the loop finishes, the function returns tot, which is 81.

Note: This is equivalent to calculating 34=813^4 = 81.

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

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