VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-fibonacci-numbers/

⇱ Sum of Fibonacci Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of Fibonacci Numbers

Last Updated : 23 Jul, 2025

Given a number positive number n, find value of f0 + f1 + f2 + .... + fn where fi indicates i'th Fibonacci number. Remember that f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ... 
Examples :

Input  : n = 3
Output : 4
Explanation : 0 + 1 + 1 + 2  = 4

Input  :  n = 4
Output :  7
Explanation : 0 + 1 + 1 + 2 + 3  = 7

[Naive Approach] By storing all Fibonacci numbers - O(n) time and O(n) space

The idea is simple we will first generate all Fibonacci numbers up to a given number n, then compute and print the sum of these Fibonacci numbers.


Output
7

Time Complexity: O(n)
Auxiliary Space: O(n)

[Better Approach] Space Optimized - O(n) time and O(1) space

This approach is just an optimization of the above approach, Instead of using the extra array for storing the Fibonacci numbers, we can store the values in the variables. We keep the previous two numbers only because that is all we need to get the next Fibonacci number in series.


Output
7

Time Complexity: O(n)
Auxiliary Space: O(1)

[Expected Approach] Efficient Fibonacci Sum Calculation - O(log(n)) time and O(n) space

The idea is to find relationship between the sum of Fibonacci numbers and n'th Fibonacci number.
F(i) refers to the i'th Fibonacci number. 
S(i) refers to sum of Fibonacci numbers till F(i), 

We can rewrite the relation F(n+1) = F(n) + F(n-1) as below
F(n-1) = F(n+1) - F(n)

Similarly,
F(n-2) = F(n) - F(n-1)
. . .
. . .
. . .
F(0) = F(2) - F(1)
-------------------------------


Adding all the equations, on left side, we have 
F(0) + F(1) + ... F(n-1) which is S(n-1).
Therefore, 
S(n-1) = F(n+1) - F(1) 
S(n-1) = F(n+1) – 1 
S(n) = F(n+2) - 1 ----(1)
In order to find S(n), simply calculate the (n+2)'th Fibonacci number and subtract 1 from the result.
F(n) can be evaluated in O(log n) time using either method 5 or method 6 in this article (Refer to methods 5 and 6).
Below is the implementation based on method 6 of this


Output
7

Time Complexity: O(log (n))
Auxiliary Space: O(n)

Comment
Article Tags: