Money, Money, Money

Instructions

Mr. Scrooge has a sum of money ‘P’ that wants to invest, and he wants to know how many years ‘Y’ this sum has to be kept in the bank in order for this sum of money to amount to ‘D’.

The sum is kept for ‘Y’ years in the bank where interest ‘I’ is paid yearly, and the new sum is re-invested yearly after paying tax ‘T’

Note that the principal is not taxed but only the year’s accrued interest

Example:

1
2
3
4
5
6
7
8
9
10
11
12
Let P be the Principal = 1000.00      
Let I be the Interest Rate = 0.05
Let T be the Tax Rate = 0.18
Let D be the Desired Sum = 1100.00


After 1st Year -->
P = 1041.00
After 2nd Year -->
P = 1083.86
After 3rd Year -->
P = 1128.30

Thus Mr. Scrooge has to wait for 3 years for the initial pricipal to ammount to the desired sum.

Your task is to complete the method provided and return the number of years ‘Y’ as a whole in order for Mr. Scrooge to get the desired sum.

Assumptions : Assume that Desired Principal ‘D’ is always greater than the initial principal, however it is best to take into consideration that if the Desired Principal ‘D’ is equal to Principal ‘P’ this should return 0 Years.


  • 이자 = 원금 * 이자율 * (1 - 세율)
  • 복리로 계산

My solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Money {
public static int calculateYears(double principal, double interest, double tax, double desired) {
if (desired <= principal)
return 0;

int year = 1;

while (true) {
double principalAfterYear = getPrincipalAfterYear(principal, interest, tax);

if (principalAfterYear >= desired)
break;

principal = principalAfterYear;
year++;
}

return year;
}

public static double getPrincipalAfterYear(double principal, double interest, double tax) {
return principal + getInterest(principal, interest, tax);
}

public static double getInterest(double principal, double interest, double tax) {
return principal * interest * (1 - tax);
}
}

Better solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Money {

public static void main(String[] args) {
System.out.println(calculateYears(1000.0, 0.05, 0.18, 1100.0));
}

public static int calculateYears(double principal, double interest, double tax, double desired) {
int year = 0;

while (principal < desired) {
principal += getInterest(principal, interest, tax);
year++;
}

return year;
}

public static double getInterest(double principal, double interest, double tax) {
return principal * interest * (1 - tax);
}
}

feeling

다른 사람의 코드를 보고 내가 너무 어렵게 접근하려 했나 라고 곰곰히 생각을 해봤다.

전에 이런 알고리즘 문제 여러개를 몇 일 동안 하루에 한 번씩 풀어 보곤 했는데 이 방식이 무식하지만 새로운 사고를 내 머리에 박기위해서 확실한 것 같다.

내가 생각지 못한 아이디어를 통해 풀은 문제의 알고리즘을 매일 따라 하면서 내 것으로 만들어야겠다.

Share