ProgrammingVery hardCapgemini · TCS NQT

A rope of length L is cut into two parts of lengths floor(L/2) and L - floor(L/2) whenever its length is 2 or more; the cost of a cut is the length L of the rope being cut. Ropes of length 1 are never cut. The function below gives the total cost of fully cutting a rope of length 12. What is printed?

A rope of length L is cut into two parts of lengths floor(L/2) and L - floor(L/2) whenever its length is 2 or more; the cost of a cut is the length L of the rope being cut. Ropes of length 1 are never cut. The function below gives the total cost of fully cutting a rope of length 12. What is printed?
function cost(L): if L <= 1 then return 0
                  return L + cost(floor(L/2)) + cost(L - floor(L/2))
Print cost(12)
  1. A. 21
  2. B. 0
  3. C. 56
  4. D. 44

Correct answer: D. 44

Each cut pays the full length of the rope being cut: 12 costs 12, the halves 6 and 6 cost 6 each, and so on, which totals 44. Dropping the second half, forgetting the cost of the cut itself, and charging 1 for each rope of length 1 each change the total.

More Pseudocode and Code Tracing questions

Exams that ask this topic