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?
- A. O(n), since each level does constant work
- B. O(n log n), like merge sort
- C. O(2^n), like the naive Fibonacci
- 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
- What is the total number of elements in a triangle of rows 1 to 10, where row k has k elements?
- A program runs a loop body 10^8 times and each iteration does one multiply and one add on ints. Roughly how long does this take on typical…
- A bit-packed bitset of 10^9 bits needs how much memory?
- Which loop is correct and fast enough to find the largest element of an array of 10^7 ints, reading each value once?
- A program must answer 10^6 queries 'is x present in the set S?' where S has 10^6 values fixed in advance. Which preprocessing and query…
- How many times does a body run in for (int i = 2; i < 100; i = i)?