Posted on by Kalkicode
Code Mathematics

Calculate compound interest

Compound interest is a financial concept where the interest earned on an investment is added to the initial investment, and in subsequent periods, interest is calculated based on the new total. This leads to exponential growth in the investment over time. It's a crucial concept in finance, banking, and investments. In this article, we'll explore how to calculate compound interest using a program.

Problem Statement

The problem is to calculate compound interest for given principal amount, time (in years), and annual interest rate. The formula for compound interest is A = P * (1 + r/n)^(nt), where:

  • A is the final amount
  • P is the principal amount
  • r is the annual interest rate
  • n is the number of times the interest is compounded per year
  • t is the time in years

Example

Let's consider an example. Suppose you invest $1000 at an annual interest rate of 5% compounded annually. After 3 years, the compound interest can be calculated as follows:

  • Principal (P) = $1000
  • Annual Interest Rate (r) = 5%
  • Time (t) = 3 years
  • Compounded annually, so n = 1

Using the formula: A = P * (1 + r/n)^(nt)

  • A = 1000 * (1 + 0.05/1)^(1*3) = 1157.63

The compound interest earned would be $157.63.

Idea to Solve

To solve this problem, we need to create a function that takes the principal amount, time, and rate as input, and then uses the formula to calculate the compound interest. The function can be implemented as follows:

Pseudocode

function compoundInterest(principal, time, rate):
    Display principal, time, and rate
    amount = principal * (1 + rate / 100)^time
    Display calculated amount as compound interest

function main():
    compoundInterest(1500, 3, 7.3)
    compoundInterest(170.4, 7, 3.4)

Algorithm Explanation

  1. The compoundInterest function takes three parameters: principal, time, and rate.
  2. It displays the provided values for principal, time, and rate.
  3. It calculates the compound interest using the formula: amount = principal * (1 + rate / 100)^time.
  4. The calculated amount is displayed as the compound interest.

Code Solution

Resultant Output Explanation

Running the provided code will give the following output:

Principal : 1500
Time : 3
Rate : 7.3
Compound Interest : 1853.06

Principal : 170.4
Time : 7
Rate : 3.4
Compound Interest : 215.334

Time Complexity

The time complexity of this code is constant, O(1), because the calculations inside the compoundInterest function involve basic arithmetic operations that don't depend on the input size. The function's execution time remains constant regardless of the input values.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment