Months to clear the loan
A loan charges whole-percent interest each month and takes a fixed monthly payment. Simulate month by month to see how long, if ever, it takes to clear.
- Each month: balance gains floor(balance × rate ÷ 100), then the payment is subtracted.
- Count a month whenever the balance is still positive at the top of the loop.
- A loan that is still not cleared after 1200 months is hopeless: return -1.
- All arithmetic is whole-unit and deterministic.
loanPayoff(loanMinor: int, monthlyPayment: int, monthlyRatePercent: int) → int
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func loanPayoff(loanMinor int, monthlyPayment int, monthlyRatePercent int) int {
}
Worked examples
| Call | Result |
|---|---|
loanPayoff(100, 30, 0) | 4 |
loanPayoff(100, 100, 0) | 1 |
loanPayoff(50, 10, 0) | 5 |
loanPayoff(100, 50, 10) | 3 |
Hint
Walk the loop with a guard count; if you run out of iterations, the debt never dies.
Reference solution in Go
func loanPayoff(loanMinor int, monthlyPayment int, monthlyRatePercent int) int {
balance, months := loanMinor, 0
for balance > 0 && months < 1200 {
balance += balance * monthlyRatePercent / 100
balance -= monthlyPayment
months++
}
if balance > 0 {
return -1
}
return months
}