The GATE Grind

GATE 2020 CS – Question 58

Programming and Data Structures · Programming in C · 2 marks · Numerical answer

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 ______.

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 81 to 81

Explanation

This is fast exponentiation computing $a^b$. tob(4) gives bits 0,0,1 with len=3. ex goes 3, 9, 81, and only the third bit is set, so tot = 81 = $3^4$.