GATE / CS ARCHIVE

SIMILAR QUESTIONS / PROGRAMMING IN C

Recognize exponentiation by repeated squaring

2 questions solved the same way, newest first. Back to Programming in C

How these are solved

Both square the base while halving or scanning the exponent and multiply selected odd/binary contributions. Derive the exponent represented by each factor.

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

Descriptive
Report issue

Recursive exponentiation

Recursion

Question 6, GATE 1994: What function of integer x,n is computed by this program?
function what(x,n):
  value := 1;
  if n > 0 then begin
    if n mod 2 = 1 then value := value*x;
    value := value*what(x*x,n div 2);
  end;
  return value;
Tap to enlarge
Answer & solution

Answer: x^n for n≥0 under exact arithmetic; 1 for n<0. (no official key was published)

1. For n≤0 the conditional is skipped and the return value is one.

2. Write positive n=2k+r, where r∈{0,1}. The function returns xr times what(x²,k).

3. Induct on n. The recursive argument k<n, and the induction hypothesis gives (x²)k. Hence the result is x2k+r=xn.

4. The recursion depth and multiplication count are O(log n). Fixed-width integer overflow can change the numerical result; no word size is specified.

Original paper, page 5