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!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

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 May 2026

Contest runs May 1 - 31. Complete challenges to climb the leaderboard!

Points are calculated for challenges completed during the contest period.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In