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)- A. 21
- B. 0
- C. 56
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Jobs each take one unit of time and carry a deadline: 1, 1, 2, 3, 4, 4 (the last slot the job may use; slots are 1, 2, 3, ...). The…
- Events (start, end) are attended one per day, and an event may be attended on any day from start to end inclusive. Events: (1,2), (1,2)…
- Seven tasks with durations 7, 5, 4, 3, 2, 2, 1 are assigned to two identical machines. Tasks are taken in decreasing duration order, and…
- Array a = [2, 5, 3, 5]. For every pair of positions i < j, count the pairs where a[i] is at most a[j] (a[i] <= a[j]). What is the printed…
- Array a = [4, -2, 5, -1, 3]. Exactly k = 2 negations are applied: each one chooses the currently smallest element and replaces it by its…
- Tasks (duration, deadline): (3,5), (2,4), (4,9), (1,3). Earliest deadline first is applied: tasks are sorted by deadline and run back to…