Reputation: 64
I'm trying to write a recursive method that takes 3 parameters (a loan amount, an interest rate, and a monthly payment). The interest is compounded monthly. The goal is to find out how many months it will take to pay off the loan completely. Here is the code I have so far:
public static double loanLength(double loan, double interest, double payment) {
if (payment > loan + loan * interest) {
return 0;
} else {
double completeLoan = loan + (loan * interest);
double stillOwe = completeLoan - payment;
if (stillOwe <= 0) {
return 1;
} else {
return 1 + (loanLength(stillOwe, interest, payment));
}
}
Examples of EXPECTED returns include:
loanLength(1000, 0.10, 200) is paid off in 6 months
loanLength(0, 0.90, 50) is 0 months
But my returns look like:
loanLength(1000, 0.10, 200): 7 months
loanLength(0, 0.90, 50): 0 months
My second test works fine, but my first one is just 1 integer above what it should be. I cannot figure out why. Any help is appreciated.
Upvotes: 0
Views: 2378
Reputation: 191844
public static int loanLength(double loan, double interestAPR, double payment) {
if (loan <= 0) {
return 0;
}
double monthlyInterest = interestAPR / (12 * 100);
double compounded = loan * (1 + monthlyInterest);
return 1 + loanLength(compounded - payment, interestAPR, payment);
}
public static void main(String[] args) {
System.out.println(loanLength(0, 0.90, 50)); // 0
System.out.println(loanLength(1000, 10.0, 200)); // 6
System.out.println(loanLength(1000, 0.1, 200)); // 6 (FWIW)
}
Please note that interest APR is expressed as is, i.e. a $10,000 loan at 10% APR and $500 monthly payments is calculated as
loanLength(10000, 10.0, 500);
If 0.10
= 10% APR, then change this line
double monthlyInterest = interestAPR / 12;
Upvotes: 3