Consider the following pseudo-code fragment, where 𝑎 and 𝑏 are integer…
2020
Consider the following pseudo-code fragment, where 𝑎 and 𝑏 are integer variables that have been initialized:
/* Pre-conditions : (𝑎>1∧𝑎<𝑏) */
/* Assume that overflow never occurs */
int 𝑥=0; int 𝑝=1;
while (𝑝<𝑏){
𝑝=𝑝∗𝑎;
𝑥=𝑥+1;
}
When the while loop terminates, what will be the value of 𝑥 in terms of 𝑎 and 𝑏?
- A.
ab
- B.
ba
- C.
⌊loga b⌋
- D.
⌈loga b⌉
Attempted by 143 students.
Show answer & explanation
Correct answer: D
Concept: When a loop repeatedly multiplies an accumulator by a constant factor a (with a > 1) until it first reaches or exceeds a threshold b, the number of multiplications needed is the smallest integer k such that ak ≥ b. By the definition of the ceiling function, that smallest k equals ⌈loga b⌉ — the discrete analogue of exponential growth crossing a fixed threshold.
Applying it to this loop:
Before the loop, x = 0 and p = 1.
Loop invariant: immediately before each condition check, p = ax (x completed multiplications so far).
The body (p = p·a; x = x + 1) runs once more each time p < b, so p climbs through the powers a, a2, a3, … as x increases.
The loop stops the very first time p ≥ b — that is, at the smallest x with ax ≥ b, which by the concept above is x = ⌈loga b⌉.
Cross-check: take a = 2, b = 10. p takes the values 2, 4, 8, 16 after x = 1, 2, 3, 4 multiplications; p first reaches/exceeds 10 at x = 4, and ⌈log2 10⌉ = ⌈3.32⌉ = 4 — matching. Equivalently, at termination ax-1 < b ≤ ax (the powers of a strictly increase since a > 1, the given pre-condition), which is exactly the defining property of x = ⌈loga b⌉.
A video solution is available for this question — log in and enroll to watch it.