ProgrammingHard

A recurrence T(n) = T(n - 1) + n is solved by a program with a loop over the recursion. What is the total cost in terms of n?

  1. A. O(n), since each level does constant work
  2. B. O(n log n), like merge sort
  3. C. O(2^n), like the naive Fibonacci
  4. D. O(n^2), since the sum 1 + 2 + ... + n is about n^2 / 2

Correct answer: D. O(n^2), since the sum 1 + 2 + ... + n is about n^2 / 2

Expanding gives T(n) = n + (n - 1) + ... + 1, which is quadratic. It is not linear because the work grows with the level.

More C Programming questions

Exams that ask this topic