recategorized by
23,653 views
78 78 votes

The following function computes $X^{Y}$ for positive integers $X$ and $Y$.

int exp (int X, int Y) { 
     int res =1, a = X, b = Y;
   
     while (b != 0) { 
         if (b % 2 == 0) {a = a * a; b = b/2; } 
         else         {res = res * a; b = b - 1; } 
     } 
     return res; 
}

Which one of the following conditions is TRUE before every iteration of the loop?

  1. $X^{Y} = a^{b}$
  2. $(res * a)^{Y} = (res * X)^{b}$
  3. $X^{Y} = res * a^{b}$
  4. $X^{Y} = (res * a)^{b}$

9 Answers

0 0 votes

Here's another good method.

Take X:2 and Y:3 (I choose them because they are prime) 

X power Y is 8

The program will have output as: But keep track of res, variable a and variable b as they are given in the option.

Now the program will run as like this:

Time 1 (after 1st iteration)res:2a:2b:2
Time 2res:2a:4b:1
Time 3res:8a:4b:0

 

On every time in each row the combination of res, a and b values is equal to X power Y for only option C.
Answer:
Position:
Show:

Related questions

74 74 votes
8 answers 8 answers
25.8k
25.8k views
Misbah Ghaya asked Feb 13, 2015
25,836 views
Consider the following pseudo code, where $x$ and $y$ are positive integers.begin q := 0 r := x while r ≥ y do begin r := r - y q := q + 1 end endThe post condition that ...
44 44 votes
6 answers 6 answers
21.8k
21.8k views
Kathleen asked Sep 18, 2014
21,804 views
Consider the following program fragment for reversing the digits in a given integer to obtain a new integer.Let $n = d_1\, d_2\, \ldots\, d_m$.int n, rev; rev = 0; while(...
33 33 votes
4 answers 4 answers
8.7k
8.7k views
Kathleen asked Sep 12, 2014
8,708 views
Consider the following PASCAL program segment:if i mod 2 = 0 then while i >= 0 do begin i := i div 2; if i mod 2 < 0 then i := i - 1; else i := i – 2; end;An appropriate...
55 55 votes
10 answers 10 answers
26.1k
26.1k views
Arjun asked Feb 14, 2017
26,121 views
Consider the C program fragment below which is meant to divide $x$ by $y$ using repeated subtractions. The variables $x$, $y$, $q$ and $r$ are all unsigned int.while (r >...