ProgrammingVery hardGoldman Sachs OA · Amazon OA
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?
for (each i from 1 to n)
for (each j from 1 to i * i)
if (j mod i == 0)
for (each k from 1 to j)
count = count + 1
end for
end if
end for
end for- A. O(n⁴)
- B. O(n⁵)
- C. O(n³)
- D. O(n² log n)
Correct answer: A. O(n⁴)
The k-loop runs only when j is a multiple of i: j = i, 2i, …, i·i, costing i + 2i + … + i·i ≈ i³/2. Summing over i gives about n⁴/8; the j-loop's own i² checks add only O(n³). So O(n⁴), not the O(n⁵) the three nested loops suggest.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What is the extra space (memory) used by the following recursive pseudocode as a function of n, counting the call stack? Function…
- What will be the output of the following pseudocode? Integer pas[0..6][0..6] = all 0 for (each i from 0 to 6) pas[i][0] = 1 for (each j…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer a[8] = {4, 9, 1, 7, 3…
- What will be the output of the following pseudocode? Integer c = 0 for (each a from 1 to 20) for (each b from a to 20) for (each h from b…
- What will be the output of the following pseudocode? String s = "Tcs NQT 2024 Exam!" Integer v = 0, c = 0, d = 0, o = 0 for (each ch in s)…
- What will be the output of the following pseudocode? String s = "AAAAA", r = "" Integer i = 0 while (i < length(s)) if (i + 1 < length(s)…