Skip to content
GATEiit

GATE CSE 2020 Q58: Value of pp(3, 4) for binary exponentiation code

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

Try it: numerical answer: type the value

Numerical answer. No negative marking.
Show answer and explanation

Answer: 81 (official GATE 2020 final answer key)

Concept used: tob writes the binary digits of b (least significant first); pp is square-and-multiply exponentiation.

First step: tob(4) gives bits 0, 0, 1 and length 3; follow tot and ex through the loop with ex = 3, 9, 81.

Full step-by-step solution

Detailed working, common mistakes and linked mock tests will be available with a free GATEiit account. Log-in is coming soon.

Share this question

WhatsAppDownload image

Source: official GATE 2020 CS question paper and final answer key, organised by IIT Delhi. Question paper · Answer key