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 _______.
Official answer and solution
- Official answer
- 81
- From
- Official GATE 2020 answer key
Solution
Trace the binary conversion function tob and the modular exponentiation loop in pp.
Trace of tob(4, arr):
- : , , .
- : , , .
- : , , .
- Loop terminates with . Returns .
- Array
arrholds binary digits of 4 in little-endian order: (representing ).
Trace of pp(3, 4):
- Initialization:
tot = 1,ex = a = 3,len = 3. - Iteration :
- :
totremains 1. ex = ex * ex = 3 * 3 = 9().
- :
- Iteration :
- :
totremains 1. ex = ex * ex = 9 * 9 = 81().
- :
- Iteration :
- :
tot = tot * ex = 1 * 81 = 81. ex = ex * ex = 81 * 81 = 6561().
- :
- Loop finishes (). Returns
tot = 81.
This function computes using repeated squaring.
Final answer
81
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2020 Computer Science and Information Technology (CS)
- Question
- 58 of 65, printed as CS Q.48
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.