The Wayback Machine - https://web.archive.org/web/20240723150231/https://www.geeksforgeeks.org/sum-fibonacci-numbers/
Open In App

Sum of Fibonacci Numbers

Last Updated : 13 Feb, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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

Method 1 (O(n)) 
Brute Force approach is pretty straightforward, find all the Fibonacci numbers till f(n) and then add them up. 
 

C++




// C++ Program to find sum of Fibonacci numbers
#include<bits/stdc++.h>
using namespace std;
 
// Computes value of first fibonacci numbers
int calculateSum(int n)
{
    if (n <= 0)
       return 0;
 
    int fibo[n+1];
    fibo[0] = 0, fibo[1] = 1;
 
    // Initialize result
    int sum = fibo[0] + fibo[1];
 
    // Add remaining terms
    for (int i=2; i<=n; i++)
    {
        fibo[i] = fibo[i-1]+fibo[i-2];
        sum += fibo[i];
    }
 
    return sum;
}
 
// Driver program to test above function
int main()
{
    int n = 4;
    cout << "Sum of Fibonacci numbers is : "
         << calculateSum(n) << endl;
    return 0;
}


Java




// Java Program to find
// sum of Fibonacci numbers
 
import java.io.*;
 
class GFG {
     
    // Computes value of first
    // fibonacci numbers
    static int calculateSum(int n)
    {
        if (n <= 0)
           return 0;
      
        int fibo[]=new int[n+1];
        fibo[0] = 0; fibo[1] = 1;
      
        // Initialize result
        int sum = fibo[0] + fibo[1];
      
        // Add remaining terms
        for (int i=2; i<=n; i++)
        {
            fibo[i] = fibo[i-1]+fibo[i-2];
            sum += fibo[i];
        }
      
        return sum;
    }
      
    // Driver program to test above function
    public static void main(String args[])
    {
        int n = 4;
        System.out.println("Sum of Fibonacci" +
        " numbers is : "+ calculateSum(n));
    }
}
 
// This code is contributed by Nikita tiwari.


Python3




# Python 3 Program to find
# sum of Fibonacci numbers
 
 
# Computes value of first
# fibonacci numbers
def calculateSum(n) :
    if (n <= 0) :
        return 0
  
    fibo =[0] * (n+1)
    fibo[1] = 1
  
    # Initialize result
    sm = fibo[0] + fibo[1]
  
    # Add remaining terms
    for i in range(2,n+1) :
        fibo[i] = fibo[i-1] + fibo[i-2]
        sm = sm + fibo[i]
         
    return sm
 
 
# Driver program to test
# above function
n = 4
print("Sum of Fibonacci numbers is : " ,
      calculateSum(n))
 
# This code is contributed
# by Nikita tiwari.


C#




// C# Program to find
// sum of Fibonacci numbers
using System;
 
class GFG
{
     
    // Computes value of first
    // fibonacci numbers
    static int calculateSum(int n)
    {
        if (n <= 0)
        return 0;
     
        int []fibo = new int[n + 1];
        fibo[0] = 0; fibo[1] = 1;
     
        // Initialize result
        int sum = fibo[0] + fibo[1];
     
        // Add remaining terms
        for (int i = 2; i <= n; i++)
        {
            fibo[i] = fibo[i - 1] + fibo[i - 2];
            sum += fibo[i];
        }
     
        return sum;
    }
     
    // Driver Code
    static void Main()
    {
        int n = 4;
        Console.WriteLine( "Sum of Fibonacci" +
                              " numbers is : "+
                              calculateSum(n));
    }
}
 
// This code is contributed by Anuj_67


PHP




<?php
// PHP Program to find sum
// of Fibonacci numbers
 
// Computes value of first
// fibonacci numbers
function calculateSum($n)
{
    if ($n <= 0)
    return 0;
 
    $fibo[0] = 0;
    $fibo[1] = 1;
 
    // Initialize result
    $sum = $fibo[0] + $fibo[1];
 
    // Add remaining terms
    for($i = 2; $i <= $n; $i++)
    {
        $fibo[$i] = $fibo[$i - 1] +
                    $fibo[$i - 2];
        $sum += $fibo[$i];
    }
 
    return $sum;
}
 
    // Driver Code
    $n = 4;
    echo "Sum of Fibonacci numbers is : ",
          calculateSum($n),"\n";
 
// This code is contributed by aj_36
?>


Javascript




<script>
// Javascript Program to find sum
// of Fibonacci numbers
 
// Computes value of first
// fibonacci numbers
function calculateSum(n)
{
    let fibo = [];
    if (n <= 0)
    return 0;
 
    fibo[0] = 0;
    fibo[1] = 1;
 
    // Initialize result
    let sum = fibo[0] + fibo[1];
 
    // Add remaining terms
    for(let i = 2; i <= n; i++)
    {
        fibo[i] = fibo[i - 1] +
                    fibo[i - 2];
        sum += fibo[i];
    }
 
    return sum;
}
 
    // Driver Code
    let n = 4;
    document.write(`Sum of Fibonacci numbers is :
        ${calculateSum(n)} <br>`);
 
// This code is contributed by _saurabh_jaiswal
</script>


Output

Sum of Fibonacci numbers is : 7

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

Method 2 : Without using extra space

C++




#include <iostream>
using namespace std;
 
int main() {
 
    int n = 4, a = 0, b = 0, sumf = 1;
    if (n<=0)
      sumf = 0;
    int curr = 1;
    for(int i = 1;i<n;i++){
        a = b;
        b = curr;
        curr = a+b;
        sumf += curr;
    }
cout<<"The sum of fibonocci numbers is:"<<sumf<<endl;
    return 0;
}


Java




import java.io.*;
 
class GFG
{
    public static void main(String args[])
    {
        int n = 4, a = 0, b = 0, sumf = 1;
        if (n <= 0)
          sumf = 0;
        int curr = 1;
        for(int i = 1; i < n; i++){
            a = b;
            b = curr;
            curr = a+b;
            sumf += curr;
        }
    System.out.println("The sum of fibonocci numbers is:"+sumf);
    }
}


Python3




#By using this code we can calculate sum of
#fibonocci numbers without using extra space
n = 4
a = 0
b = 0
sumf = 1
if n<=0:
  sumf = 0
curr = 1
for i in range(1,n):
  a = b
  b = curr
  curr = a+b
  sumf += curr
print("The sum of fibonocci numbers is:",sumf)


Javascript




let n = 4, a = 0, b = 0, sumf = 1;
if (n<=0)
  sumf = 0;
let curr = 1;
for(let i = 1;i<n;i++){
    a = b;
    b = curr;
    curr = a+b;
    sumf += curr;
}
console.log("The sum of fibonocci numbers is:"+sumf);
  


C#




using System;
using System.Collections.Generic;
 
class Gfg
{
    public static void Main(string[] args)
    {
        int n = 4, a = 0, b = 0, sumf = 1;
        if (n<=0)
            sumf = 0;
        int curr = 1;
        for(int i = 1;i<n;i++){
            a = b;
            b = curr;
            curr = a+b;
            sumf += curr;
        }
        Console.Write("The sum of fibonocci numbers is:"+sumf);
    }
}


Output

The sum of fibonocci numbers is:7

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

Method 3 (O(Log n)) 
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 
 

C++




// C++ Program to find sum of Fibonacci numbers in
// O(Log n) time.
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1000;
 
// Create an array for memoization
int f[MAX] = {0};
 
// Returns n'th Fibonacci number using table f[]
int fib(int n)
{
    // Base cases
    if (n == 0)
        return 0;
    if (n == 1 || n == 2)
        return (f[n] = 1);
 
    // If fib(n) is already computed
    if (f[n])
        return f[n];
 
    int k = (n & 1)? (n+1)/2 : n/2;
 
    // Applying above formula [Note value n&1 is 1
    // if n is odd, else 0].
    f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1))
           : (2*fib(k-1) + fib(k))*fib(k);
 
    return f[n];
}
 
// Computes value of first Fibonacci numbers
int calculateSum(int n)
{
    return fib(n+2) - 1;
}
 
// Driver program to test above function
int main()
{
    int n = 4;
    cout << "Sum of Fibonacci numbers is : "
         << calculateSum(n) << endl;
    return 0;
}


Java




// Java Program to find sum of Fibonacci numbers in
// O(Log n) time.
import java.util.*;
 
class GFG{
static int MAX = 1000;
 
// Create an array for memoization
static int []f = new int[MAX];
 
// Returns n'th Fibonacci number using table f[]
static int fib(int n)
{
   
    // Base cases
    if (n == 0)
    return 0;
    if (n == 1 || n == 2)
        return (f[n] = 1);
 
    // If fib(n) is already computed
    if (f[n]>0)
        return f[n];
 
    int k = ((n & 1)>0)? (n+1)/2 : n/2;
 
    // Applying above formula [Note value n&1 is 1
    // if n is odd, else 0].
    f[n] = (n & 1)>0? (fib(k)*fib(k) + fib(k-1)*fib(k-1))
           : (2*fib(k-1) + fib(k))*fib(k);
 
    return f[n];
}
 
// Computes value of first Fibonacci numbers
static int calculateSum(int n)
{
    return fib(n+2) - 1;
}
 
// Driver program to test above function
public static void main(String[] args)
{
    int n = 4;
    System.out.print("Sum of Fibonacci numbers is : "
         + calculateSum(n) +"\n");
}
}
 
// This code is contributed by gauravrajput1


Python3




# Python 3 Program to find sum of
# Fibonacci numbers in O(Log n) time.
 
MAX = 1000
 
# Create an array for memoization
f = [0] * MAX
 
# Returns n'th Fibonacci number
# using table f[]
def fib(n):
     
    n = int(n)
 
    # Base cases
    if (n == 0):
        return 0
    if (n == 1 or n == 2):
        return (1)
 
    # If fib(n) is already computed
    if (f[n] == True):
        return f[n]
 
    k = (n+1)/2 if (n & 1) else n/2
 
    # Applying above formula [Note value n&1
    # is 1 if n is odd, else 0].
    f[n] = (fib(k) * fib(k) + fib(k-1) * fib(k-1)) if (n & 1) else (2 * fib(k-1) + fib(k)) * fib(k)
    return f[n]
 
# Computes value of first Fibonacci numbers
def calculateSum(n):
 
    return fib(n+2) - 1
 
# Driver program to test above function
n = 4
print("Sum of Fibonacci numbers is :", calculateSum(n))
 
# This code is contributed by
# Smitha Dinesh Semwal


C#




// C# Program to find sum
// of Fibonacci numbers in
// O(Log n) time.
using System;
 
class GFG {
    static int MAX = 1000;
 
    // Create an array for memoization
    static int []f = new int[MAX];
     
    // Returns n'th Fibonacci
    // number using table f[]
    static int fib(int n)
    {
        for(int i = 0;i < MAX;i++)
        f[i] = 0;
         
        //Arrays.fill(f, 0);
        // Base cases
        if (n == 0)
            return 0;
        if (n == 1 || n == 2)
            return (f[n] = 1);
     
        // If fib(n) is
        // already computed
        if (f[n] == 1)
            return f[n];
            int k;
        if((n & 1) == 1)
            k = (n + 1) / 2 ;
        else
            k = n / 2;
     
        // Applying above formula
        // [Note value n&1 is 1
        // if n is odd, else 0].
        if((n & 1) == 1)
            f[n] = (fib(k) * fib(k) + fib(k - 1)
                                   * fib(k - 1));
        else
            f[n] = (2 * fib(k - 1) + fib(k)) *
                                       fib(k);
     
        return f[n];
    }
     
    // Computes value of first
    // Fibonacci numbers
    static int calculateSum(int n)
    {
        return fib(n + 2) - 1;
    }
     
    // Driver Code
    public static void Main()
    {
        int n = 4;
        Console.Write( "Sum of Fibonacci numbers is : "
                                    + calculateSum(n));
         
    }
}
 
// This code is contributed by nitin mittal.


PHP




<?php
// PHP Program to find sum of Fibonacci
// numbers in O(Log n) time.
$MAX = 1000;
 
// Create an array for memoization
$f = array_fill(0, $MAX, 0);
 
// Returns n'th Fibonacci number
// using table f[]
function fib($n)
{
    global $f;
     
    // Base cases
    if ($n == 0)
        return 0;
    if ($n == 1 || $n == 2)
        return ($f[$n] = 1);
 
    // If fib(n) is already computed
    if ($f[$n])
        return $f[$n];
 
    $k = ($n & 1) ? ($n + 1) / 2 : $n / 2;
 
    // Applying above formula [Note value n&1
    // is 1 if n is odd, else 0].
    $f[$n] = ($n & 1) ?
             (fib($k) * fib($k) + fib($k - 1) * fib($k - 1)) :
                  (2 * fib($k - 1) + fib($k)) * fib($k);
 
    return $f[$n];
}
 
// Computes value of first Fibonacci numbers
function calculateSum($n)
{
    return fib($n + 2) - 1;
}
 
// Driver Code
$n = 4;
print("Sum of Fibonacci numbers is : " .
                      calculateSum($n));
 
// This code is contributed by mits
?>


Javascript




<script>
// javascript Program to find sum of Fibonacci numbers in
// O(Log n) time.
    var MAX = 1000;
 
    // Create an array for memoization
     var f = Array(MAX).fill(0);
 
    // Returns n'th Fibonacci number using table f
    function fib(n) {
 
        // Base cases
        if (n == 0)
            return 0;
        if (n == 1 || n == 2)
            return (f[n] = 1);
 
        // If fib(n) is already computed
        if (f[n] > 0)
            return f[n];
 
        var k = ((n & 1) > 0) ? (n + 1) / 2 : n / 2;
 
        // Applying above formula [Note value n&1 is 1
        // if n is odd, else 0].
        f[n] = (n & 1) > 0 ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k);
 
        return f[n];
    }
 
    // Computes value of first Fibonacci numbers
    function calculateSum(n) {
        return fib(n + 2) - 1;
    }
 
    // Driver program to test above function
        var n = 4;
        document.write("Sum of Fibonacci numbers is : " + calculateSum(n) + "\n");
 
// This code is contributed by gauravrajput1
</script>


Output

Sum of Fibonacci numbers is : 7

Time Complexity: O(logn)
Auxiliary Space: O(MAX)

 



Previous Article
Next Article

Similar Reads

Check if sum of Fibonacci elements in an Array is a Fibonacci number or not
Given an array arr[] containing N elements, the task is to check if the sum of Fibonacci elements of the array is a fibonacci number or not.Examples: Input: arr[] = {2, 3, 7, 11} Output: Yes Explanation: As there are two Fibonacci numbers in the array i.e. 2 and 3. So, the sum of Fibonacci numbers is 2 + 3 = 5 and 5 is also a Fibonacci number. Inpu
7 min read
Check if a M-th fibonacci number divides N-th fibonacci number
Given two numbers M and N, the task is to check if the M-th and N-th Fibonacci numbers perfectly divide each other or not.Examples: Input: M = 3, N = 6 Output: Yes F(3) = 2, F(6) = 8 and F(6) % F(3) = 0 Input: M = 2, N = 9 Output: Yes A naive approach will be to find the N-th and M-th Fibonacci numbers and check if they are perfectly divisible or n
8 min read
Number of ways to represent a number as sum of k fibonacci numbers
Given two numbers N and K. Find the number of ways to represent N as the sum of K Fibonacci numbers. Examples: Input : n = 12, k = 1 Output : 0 Input : n = 13, k = 3 Output : 2 Explanation : 2 + 3 + 8, 3 + 5 + 5. Approach: The Fibonacci series is f(0)=1, f(1)=2 and f(i)=f(i-1)+f(i-2) for i&gt;1. Let's suppose F(x, k, n) be the number of ways to for
8 min read
Sum of Fibonacci Numbers with alternate negatives
Given a positive integer n, the task is to find the value of F1 - F2 + F3 -..........+ (-1)n+1Fn where Fi denotes i-th Fibonacci number.Fibonacci Numbers: The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .... In mathematical terms, the sequence Fn of Fibonacci numbers is defined
12 min read
Sum of numbers from 1 to N which are in Fibonacci Sequence
Given an integer N, the task is to find the sum of numbers from 1 to N which are in Fibonacci sequence. First few Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, ....Examples: Input: N = 5 Output: 12 1 + 1 + 2 + 3 + 5 = 12Input: N = 10 Output: 20 1 + 1 + 2 + 3 + 5 + 8 = 20 Approach: Loop through all the Fibonacci numbers which are less than N.I
4 min read
Sum of Fibonacci Numbers in a range
Given a range [l, r], the task is to find the sum fib(l) + fib(l + 1) + fib(l + 2) + ..... + fib(r) where fib(n) is the nth Fibonacci number. Examples: Input: l = 2, r = 5 Output: 11 fib(2) + fib(3) + fib(4) + fib(5) = 1 + 2 + 3 + 5 = 11 Input: l = 4, r = 8 Output: 50 Naive approach: Simply calculate fib(l) + fib(l + 1) + fib(l + 2) + ..... + fib(r
8 min read
Sum of all Non-Fibonacci numbers in a range for Q queries
Given Q queries containing ranges in the form of [L, R], the task is to find the sum of all non-fibonacci numbers for each range in the given queries.Examples: Input: arr[][] = {{1, 5}, {6, 10}} Output: 4 32 Explanation: Query 1: In the range [1, 5], only 4 is a non-fibonacci number. Query 2: In the range [6, 10], 6, 7, 9 and 10 are the non-fibonac
8 min read
Sum of numbers in the Kth level of a Fibonacci triangle
Given a number K, the task is to find the sum of numbers at the Kth level of the Fibonacci triangle.Examples: Input: K = 3 Output: 10 Explanation: Fibonacci triangle till level 3: 0 1 1 2 3 5 Sum at 3rd level = 2 + 3 + 5 = 10 Input: K = 2 Output: 2 Explanation: Fibonacci triangle till level 3: 0 1 1 Sum at 3rd level = 1 + 1 = 2 Approach: Till Kth l
6 min read
Find two Fibonacci numbers whose sum can be represented as N
Given an even number N, the task is to find two Fibonacci numbers whose sum can be represented as N. There may be several combinations possible. Print only first such pair. If there is no solution then print -1.Examples: Input: N = 90 Output: 1, 89 Explanation: The first pair with whose sum is equal to 90 is {1, 89}Input: N = 74 Output: -1 Approach
6 min read
Sum and product of K smallest and largest Fibonacci numbers in the array
Given an integer K and an array arr[] containing N integers, the task is to find the sum and product of K smallest and K largest fibonacci numbers in the array. Note: Assume that there are at least K fibonacci numbers in the array. Examples: Input: arr[] = {2, 5, 6, 8, 10, 11}, K = 2 Output: Sum of K-minimum fibonacci numbers is 7 Product of K-mini
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg