Back to questions
For this Fintech company, you need to build a compound interest calculator, using the four variables below as input:
Principal: This is the starting amount you put into the account. It’s the base amount that will start earning interest right away.
Interest Rate: This is the percentage of your current balance that the bank adds to your account as interest each year. For example, a 5% interest rate means the bank will add 5% of your balance to your account every year.
Annual Contribution: This is a fixed amount you add to your investment at the end of each year, like a regular deposit you decide to make. Each time you make this contribution, it increases your balance, which in turn, increases the amount of interest you earn next year (since interest is calculated on the new, larger balance).
Years to Invest: This is how long your money stays in the account, compounding annually. The longer you invest, the more times your balance grows, not only from the interest but also from the additional contributions.
Using these four values, calculate the final amount you’ll have after the specified number of years, with annual compounding. In other words, at the end of each year, you’ll earn interest on your current balance, then make an additional contribution.
Return the answer rounded to two decimal places.
Input:
principal | rate | contribution | years |
---|---|---|---|
500 | 10 | 50 | 3 |
Output: 831.00
Explanation:
Input:
principal | rate | contribution | years |
---|---|---|---|
1000 | 20 | 100 | 10 |
Output: 8,787.60
p.s. for a mathematical challenge, can you code this up without iteration (no for/while loop, in O(1) time)?
We'll calculate the total amount by iterating over each year, updating the amount with interest, and adding the contribution at the end of each year.
This approach uses the compound interest formula to calculate the final amount directly, incorporating both the initial investment and the yearly contributions. This method is efficient and avoids looping.
The formula for compound interest with annual contributions is:
where:
The formula consists of two parts:
Here's the code: