Consider the following C code. Assume that unsigned long int type length is bits.
unsigned long int fun(unsigned long int n) {
unsigned long int i, j=0, sum = 0;
for( i=n; i>1; i=i/2) j++;
for( ; j>1; j=j/2) sum++;
return sum;
}
The value returned when we call fun with the input is:
View worked solution
Answer: B
To find the value returned by fun(2^{40}), let's analyze the two loops step-by-step.
Step 1: Analyzing the First Loop
for( i=n; i>1; i=i/2) j++;
This loop starts with and repeatedly divides by until . Since is halved in each step, the loop runs exactly times.
- For , the loop executes times.
- Therefore, the value of after the first loop terminates is .
Step 2: Analyzing the Second Loop
for( ; j>1; j=j/2) sum++;
This loop starts with the current value of and repeatedly divides by (using integer division) until . Let's trace the iterations:
| Iteration | Current () | New sum |
Next (after j = j/2) |
|---|---|---|---|
| 1 | (True) | ||
| 2 | (True) | ||
| 3 | (True) | ||
| 4 | (True) | (integer division) | |
| 5 | (True) | ||
| 6 | (False) | Loop terminates |
When the loop terminates, the value of sum is , which is returned by the function.
Thus, the correct option is B.
Free practice · Your answers on this page are not saved.
