ProgrammingHard
A function computes the sum of 1 to n by recursion with depth n. For n = 10^6, what is the main risk?
- A. The sum overflows 64-bit integers
- B. The function returns a pointer to a local
- C. The recursion depth can overflow the call stack, so an iterative loop or a formula is safer
- D. The recursion is too shallow to be correct
Correct answer: C. The recursion depth can overflow the call stack, so an iterative loop or a formula is safer
A million nested calls use a lot of stack space, which may overflow. A loop or the closed form n(n+1)/2 avoids the depth.
More C Programming questions
- A program increments a counter inside three nested loops, each running n = 100 times. How many increments occur?
- In a loop for (i = 0; i < n; i++) x = x 2 % m; with m = 1000000007 and x kept as long long, what is the cost?
- Which loop computes the number of trailing zeros of n in O(number of zeros) time for an unsigned n greater than zero?
- A loop with i starting at 1 and i = 2 until i > n runs how many times for n = 1000?
- A program uses a while loop that finds the smallest power of two at least n for n = 1000, starting from 1. What value does it return?
- int i = 0; for (; i < 5; ) i += 2; printf("%d", i); What is printed?