Calculate compound interest given principal amount, annual interest rate, compounding frequency per year, and time in years. Use the compound interest formula: A = P(1 + r/n)^(nt) where A is the final amount, P is the principal, r is the annual rate (as a decimal), n is the compounding frequency, and t is the time in years.
Return the final amount rounded to 2 decimal places. If any input is null or invalid (negative values or zero compounding frequency), return null.
Examples:
Input: principal = 1000, annualRate = 0.05, compoundsPerYear = 12, years = 10
Output: 1647.01
Explanation: 1000 * (1 + 0.05/12)^(12*10) = 1647.01
Input: principal = 5000, annualRate = 0.08, compoundsPerYear = 4, years = 5
Output: 7429.74
Explanation: 5000 * (1 + 0.08/4)^(4*5) = 7429.74
Input: principal = -100, annualRate = 0.05, compoundsPerYear = 1, years = 5
Output: null
Explanation: Negative principal is invalid
Apex Code Editor
Welcome to Lightning Challenge!
Create an Account
Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.
Create accountHow It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Note
You can test your code by connecting to Salesforce, but to save your progress and earn points, you'll need to create an account. Your solutions and achievements will be tracked automatically once you're logged in.