Months to reach a savings target
A plan asks how many whole months of flat saving are needed to top up a target balance.
- Every month the same whole amount is set aside, in minor units.
- A target of zero or less needs no saving at all.
- A monthlySaving of zero or less can never get there.
- Round months up — any partial month still costs a full one.
months_to_target(target: int, monthly_saving: int) → int
Where you start
def months_to_target(target: int, monthly_saving: int) -> int:
Worked examples
| Call | Result |
|---|---|
months_to_target(1000, 300) | 4 |
months_to_target(1000, 500) | 2 |
months_to_target(1000, 1000) | 1 |
months_to_target(0, 500) | 0 |
Hint
Ceil(target / saving) via (target + saving - 1) / saving.
Reference solution in Python
def months_to_target(target: int, monthly_saving: int) -> int:
if target <= 0 or monthly_saving <= 0:
return 0
return (target + monthly_saving - 1) // monthly_saving