Python Program to Calculate Compound Interest
A = P * (1 + r/n) ** (n * t), where P is principal, r is annual rate (decimal), n is times compounded per year, and t is years; then compound interest is A - P.Examples
How to Think About It
A = P * (1 + r/n) ** (n * t) to find the total amount after interest. Then subtract the principal P from this total to get the compound interest earned.Algorithm
Code
P = float(input('Enter principal amount: ')) r = float(input('Enter annual interest rate (in %): ')) / 100 n = int(input('Enter number of times interest compounded per year: ')) t = float(input('Enter time in years: ')) A = P * (1 + r / n) ** (n * t) compound_interest = A - P print(f'Compound Interest: {compound_interest:.2f}')
Dry Run
Let's trace the example with P=1000, r=5%, n=4, t=1 through the code
Input values
P=1000, r=5% converted to 0.05, n=4, t=1
Calculate total amount A
A = 1000 * (1 + 0.05/4) ** (4 * 1) = 1000 * (1 + 0.0125) ** 4 = 1000 * 1.050945 = 1050.945
Calculate compound interest
Compound Interest = 1050.945 - 1000 = 50.945
Print result
Compound Interest: 50.95 (rounded)
| Step | Calculation | Value |
|---|---|---|
| Calculate A | 1000 * (1 + 0.05/4) ** 4 | 1050.945 |
| Compound Interest | 1050.945 - 1000 | 50.945 |
Why This Works
Step 1: Convert rate to decimal
The interest rate is given in percent, so dividing by 100 converts it to decimal form for calculation.
Step 2: Apply compound interest formula
The formula A = P * (1 + r/n) ** (n * t) calculates the total amount including interest compounded multiple times per year.
Step 3: Find compound interest
Subtracting the original principal P from the total amount A gives the compound interest earned.
Alternative Approaches
def compound_interest(P, r, n, t): A = P * (1 + r / n) ** (n * t) return A - P print(f'Compound Interest: {compound_interest(1000, 0.05, 4, 1):.2f}')
import math P = 1000 r = 0.05 n = 4 t = 1 A = P * math.pow((1 + r / n), n * t) print(f'Compound Interest: {A - P:.2f}')
Complexity: O(1) time, O(1) space
Time Complexity
The calculation uses a fixed number of arithmetic operations and exponentiation, so it runs in constant time.
Space Complexity
Only a few variables are used to store inputs and results, so space usage is constant.
Which Approach is Fastest?
Both the direct formula and using math.pow() run in constant time; using a function adds clarity but no significant speed difference.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct formula with ** operator | O(1) | O(1) | Simple scripts |
| Function-based approach | O(1) | O(1) | Reusable code and multiple calculations |
| Using math.pow() | O(1) | O(1) | When preferring math module functions |