GATE / CS ARCHIVE

GATE CSE 1994 / QUESTION 6

Recursive exponentiation

Programming in C · Recursion · Full GATE CSE 1994 paper

GATE 1994, Q6 Descriptive
Report issue

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