Greedy Algorithms8 sections · 316 units
Open in Course

Broken Calculator - Implementation

The code

Here is the solution:

function brokenCalc(X, Y)
 ops := 0
 while Y > X
 if Y % 2 = 0 then
 Y := Y / 2
 else
 Y := Y + 1
 ops := ops + 1
 return ops + (X - Y)

Time: O(logY)O(\log Y). Space: O(1)O(1).

Once YXY \leq X, you cannot halve anymore (would go below XX). Just add the difference.