ProgrammingVery hardProduct company OA · code-tracing level
What is the time complexity of the following pseudocode, as a function of n?
What is the time complexity of the following pseudocode, as a function of n?
i = 2
while (i <= n)
i = i * i
end while- A. O(log n)
- B. O(√n)
- C. O(log log n)
- D. O(1)
Correct answer: C. O(log log n)
i goes 2, 4, 16, 256, 65536, …: after k steps i = 2^(2^k). The loop stops once 2^(2^k) > n, i.e. 2^k > log₂ n, k > log₂ log₂ n. So it runs O(log log n) times. O(log n) is the answer for i = i * 2, where the exponent grows by 1 each step instead of doubling.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What is the time complexity of the following pseudocode, as a function of n? for (i = 1; i i <= n; i = i + 1) for (j = 1; j <= n; j = j 2)…
- What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division; 'from … to …' includes both ends.)…
- What will be the output of the following pseudocode? Integer c = 0, d, k for (each x from 1 to 30) k = 0 for (each d from 1 to x) if (x…
- What will be the output of the following pseudocode? (Array positions run from 1 to 10.) Integer alive[1..10] = all 1, left = 10, pos = 0…
- What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, << and >> are shifts.) Integer x = 22, r = 0 for…
- What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division.) Integer a[7] = {1, 3, 5, 5, 5, 7…