Drill

ProblemsJavaScript › finance

Months to clear the loan

hardfinanceJavaScript

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.

loanPayoff(loanMinor: int, monthlyPayment: int, monthlyRatePercent: int) → int

Solve it in the editor →

Where you start

function loanPayoff(loanMinor, monthlyPayment, monthlyRatePercent) {
  
}

Worked examples

CallResult
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 JavaScript
function loanPayoff(loanMinor, monthlyPayment, monthlyRatePercent) {
  let balance = loanMinor;
  let months = 0;
  while (balance > 0 && months < 1200) {
    balance += Math.floor((balance * monthlyRatePercent) / 100);
    balance -= monthlyPayment;
    months++;
  }
  return balance > 0 ? -1 : months;
}

The same problem in another language

More finance problems in JavaScript