GATE / CS ARCHIVE

GATE CSE 2020 / QUESTION 48

GATE CSE 2020 Q48

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2020 paper

GATE 2020, Q48 2 marks · NAT
Report issue

Control Flow & Loop Tracing

Question 48, GATE 2020: Find pp(3,4) for these 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;
}
Question 48, GATE 2020: Find pp(3,4) for these 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;
}
Tap to enlarge
Answer & solution

Official answer: 81

Worked explanation

The first loop extracts bits from least significant to most significant. Its trace (b before division, stored bit) is (4,0),(2,0),(1,1), then b=0 and len=3. The second loop trace (i,bit,ex before squaring,tot after possible multiply) is (0,0,3,1),(1,0,9,1),(2,1,81,81). Squaring ex is outside the if, so it happens on all iterations; that placement is central. The final ex=6561 is not the returned variable. More generally the loop multiplies powers a2^i for the set bits of b, implementing exponentiation by repeated squaring, so pp(3,4)=34=81.

Derivation and answer

tob(4, arr) stores the low-to-high binary digits 0, 0, 1 and returns len=3. In pp, ex is successively 3, 9, 81. Only the third digit is 1, so tot changes from 1 to 81 then. The final squaring makes ex=6561 but does not change tot. Thus pp(3, 4) returns 81. All values here fit even a 16-bit signed int, so overflow does not alter this evaluation.

Original paper, page 15 · Answer key