Given a positive integer n, calculate the sum of the first n Fibonacci numbers. The Fibonacci sequence starts with 0, 1, 1, 2, 3, 5, 8, 13, and so on, where each number is the sum of the two preceding numbers. Return 0 for null or non-positive input.
public static Long fibonacciSum(Integer n)
Examples:
Input: n = 1
Output: 0
Explanation: First Fibonacci number is 0
Input: n = 5
Output: 7
Explanation: 0 + 1 + 1 + 2 + 3 = 7
Input: n = 6
Output: 12
Explanation: 0 + 1 + 1 + 2 + 3 + 5 = 12
Input: n = null
Output: 0
Apex Code Editor
Welcome to Lightning Challenge!
How 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
Contest Alert
🏆 #CodeEveryDay July 2026
Contest runs July 1 - 31. Complete challenges to climb the leaderboard!
Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.