With preconditions p ≥ 1 and n ≥ 0 (no overflow): int x = p; int k = n; int m = 1; while (k != 0) { if (k is odd) m = m * x; x = x * x; k = floor(k / 2); } The loop invariant is m·xᵏ = pⁿ and k ≥ 0. Which must be true at the end?
Pick an option to check yourself, or open the answer below.
Show answer & explanation
Correct answer: B. m = pⁿ
Explanation
When the loop ends k = 0, so the invariant m·x⁰ = pⁿ gives m = pⁿ (fast exponentiation).
More Data Structures and Algorithms questions
- Match List I with List II. List I: (a) Prim's algorithm, (b) Dijkstra's algorithm, (c) Faster all-pairs shortest path, (d) Edmonds-Karp alg…
- There are many sorting algorithms based on comparison. The running time of heapsort O(n lg n) P Q algorithm is . Like , but unlike , (P, Q)…
- Which of the following is best running time to n n2 − 1 sort integers in the range 0 to ?
- Which of the following is application of depth- first search?
- Consider double hashing of the form h(k, i) = (h (k) + ih (k)) mod m 1 2 h (k) = k mod m where 1 h (k) = 1 + (k mod n) 2 n = m − 1 m = 701…
- Consider the complexity class as the ¯¯¯ L ∈ NP set of languages L such that , and the following two statements : S : P ⊆ CO − NP 1 S NP ≠…