Question

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) is _______.

Official answer and solution
Official answer
81
From
Official GATE 2020 answer key

Solution

Trace the binary conversion function tob and the modular exponentiation loop in pp.

Trace of tob(4, arr):

  • b=4b = 4: b%2=0  ⟹  arr[0]=0b \% 2 = 0 \implies \text{arr}[0] = 0, b=2b = 2, i=1i = 1.
  • b=2b = 2: b%2=0  ⟹  arr[1]=0b \% 2 = 0 \implies \text{arr}[1] = 0, b=1b = 1, i=2i = 2.
  • b=1b = 1: b%2=1  ⟹  arr[2]=1b \% 2 = 1 \implies \text{arr}[2] = 1, b=0b = 0, i=3i = 3.
  • Loop terminates with i=3i = 3. Returns len=3\text{len} = 3.
  • Array arr holds binary digits of 4 in little-endian order: arr[0]=0,arr[1]=0,arr[2]=1\text{arr}[0] = 0, \text{arr}[1] = 0, \text{arr}[2] = 1 (representing 4=0⋅20+0⋅21+1⋅224 = 0 \cdot 2^0 + 0 \cdot 2^1 + 1 \cdot 2^2).

Trace of pp(3, 4):

  • Initialization: tot = 1, ex = a = 3, len = 3.
  • Iteration i=0i = 0:
    • arr[0]==0\text{arr}[0] == 0: tot remains 1.
    • ex = ex * ex = 3 * 3 = 9 (323^2).
  • Iteration i=1i = 1:
    • arr[1]==0\text{arr}[1] == 0: tot remains 1.
    • ex = ex * ex = 9 * 9 = 81 (343^4).
  • Iteration i=2i = 2:
    • arr[2]==1\text{arr}[2] == 1: tot = tot * ex = 1 * 81 = 81.
    • ex = ex * ex = 81 * 81 = 6561 (383^8).
  • Loop finishes (i=3i = 3). Returns tot = 81.

This function computes ab=34=81a^b = 3^4 = 81 using repeated squaring.

Final answer

81

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2020 Computer Science and Information Technology (CS)
Question
58 of 65, printed as CS Q.48
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.