ProgrammingModerate
Which statement about the nested loop for (i = 0; i < n; i++) for (j = 1; j < n; j *= 2) is correct?
- A. It runs about n log2 n iterations in total
- B. It runs about n^2 iterations
- C. It runs about n iterations, since the inner loop is constant
- D. It runs about n^2 / 2 iterations
Correct answer: A. It runs about n log2 n iterations in total
The inner loop doubles j, so it has about log2 n steps for each of the n values of i.
More C Programming questions
- Which operation is O(1) in a C array, but O(n) in a singly linked list when the head is given?
- A program reads a number n and then loops for (i = 0; i < n; i++) with n = 10^9 and a constant body. Roughly how long does it take in C…
- Which operation makes a sorted array of n elements support lookup in O(log n) and insertion in O(n)?
- For a char buffer of length 10^6 that is processed once, which loop is correct and fast enough?
- A matrix of 3000 x 3000 cells is read once and each cell is visited a constant number of times. Which complexity bound applies to the…
- A recursive merge sort on 10^6 elements makes how many comparisons, roughly?