Consider the pseudo-code fragment, where m is a non-negative integer that has been initialized:
p = 0;
k = 0;
while (k < m)
p = p + 2^k;
k = k + 1;
end whileWhich of the following is a loop invariant for the while statement? (A loop invariant is an assertion that is true each time the guard is evaluated.)
Pick an option to check yourself, or open the answer below.
Show answer & explanation
Correct answer: C. p = 2^k − 1 and 0 ≤ k ≤ m
Explanation
At each guard test p = 2⁰ + … + 2^(k−1) = 2^k − 1 (k = 0 gives p = 0). The guard is also evaluated one last time with k = m, so the bound must be 0 ≤ k ≤ m.
Note on the official key: the official key says option B. Official key gives (B), but p = 2^(k+1) − 1 already fails at the start (k = 0, p = 0), and k < m fails on the last guard test when k = m.
More Data Structures and Algorithms questions
- The solution of the recurrence relation T(m) = T(3 m/4) + 1 is :
- Consider the array A=<4, 1, 3, 2, 16, 9, 10, 14, 8, 7>. After building heap from the array A, the depth of the heap and the right child of…
- Which of the following algorithms solves the single-source shortest paths ?
- A text is made up of the characters A, B, C, D, E each occurring with the probability 0.08, 0.40, 0.25, 0.15 and 0.12 respectively. The opt…
- A binary search tree in which every non-leaf node has non-empty left and right subtrees is called a strictly binary tree. Such a tree with…
- Match the following with respect to algorithm paradigms :