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 is _______.
View worked solution
Answer: 81
The function pp(a, b) implements the standard binary exponentiation (or exponentiation by squaring) algorithm to compute . Let us trace the execution for pp(3, 4) step-by-step.
Step 1: Trace of tob(4, arr)
The function tob(b, arr) converts the integer into its binary representation and stores the bits in arr in least-significant-bit (LSB) first order. It returns the number of bits (length).
For :
- Iteration 1 (): . Since ,
arr[0] = 0. Then . - Iteration 2 (): . Since ,
arr[1] = 0. Then . - Iteration 3 (): . Since ,
arr[2] = 1. Then .
The loop terminates because . The function returns i = 3. Thus, len = 3 and arr = {0, 0, 1}.
Step 2: Trace of pp(3, 4)
We initialize ex = a = 3, tot = 1, and len = 3. The loop runs for :
| Iteration () | arr[i] |
Condition arr[i] == 1 |
Value of tot |
Next Value of ex (ex * ex) |
|---|---|---|---|---|
| False | ||||
| False | ||||
| True |
After the loop finishes, the function returns tot, which is 81.
Note: This is equivalent to calculating .
Free practice · Your answers on this page are not saved.
