Sum of squares of Fibonacci numbers - GeeksforGeeks

14 Sep, 2021
Given a positive integer N. The task is to find the sum of squares of all Fibonacci numbers up to N-th fibonacci number. That is,  
f02 + f12 + f22+.......+fn2 

where fi indicates i-th fibonacci number.
Fibonacci numbers: f0=0 and f1=1 and fi=fi-1 + fi-2 for all i>=2.Examples:  
Input: N = 3
Output: 6
Explanation: 0 + 1 + 1 + 4 = 6

Input: N = 6
Output: 104
Explanation: 0 + 1 + 1 + 4 + 9 + 25 + 64 = 104
 
Method 1: Find all Fibonacci numbers till N and add up their squares. This method will take O(n) time complexity.Below is the implementation of this approach:  
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find sum of// squares of Fibonacci numbers#include <bits/stdc++.h>using namespace std; // Function to calculate sum of// squares of Fibonacci numbersint calculateSquareSum(int n){    if (n <= 0)        return 0;     int fibo[n + 1];    fibo[0] = 0, fibo[1] = 1;     // Initialize result    int sum = (fibo[0] * fibo[0]) + (fibo[1] * fibo[1]);     // Add remaining terms    for (int i = 2; i <= n; i++) {        fibo[i] = fibo[i - 1] + fibo[i - 2];        sum += (fibo[i] * fibo[i]);    }     return sum;} // Driver program to test above functionint main(){    int n = 6;     cout << "Sum of squares of Fibonacci numbers is : "         << calculateSquareSum(n) << endl;     return 0;}
// Java Program to find sum of// squares of Fibonacci numbers   public class Improve {          // Function to calculate sum of    // squares of Fibonacci numbers    static int calculateSquareSum(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[0]) + (fibo[1] * fibo[1]);               // Add remaining terms        for (int i = 2; i <= n; i++) {            fibo[i] = fibo[i - 1] + fibo[i - 2];            sum += (fibo[i] * fibo[i]);        }               return sum;    }           // Driver code    public static void main(String args[])    {           int n = 6;           System.out.println("Sum of squares of Fibonacci numbers is : " +                                calculateSquareSum(n));               }    // This Code is contributed by ANKITRAI1}
# Python3 Program to find sum of# squares of Fibonacci numbers # Function to calculate sum of# squares of Fibonacci numbersdef calculateSquareSum(n):    fibo = [0] * (n + 1);    if (n <= 0):        return 0;    fibo[0] = 0;    fibo[1] = 1;         # Initialize result    sum = ((fibo[0] * fibo[0]) +           (fibo[1] * fibo[1]));         # Add remaining terms    for i in range(2, n + 1):        fibo[i] = (fibo[i - 1] +                   fibo[i - 2]);        sum += (fibo[i] * fibo[i]);     return sum; # Driver Coden = 6; print("Sum of squares of Fibonacci numbers is :",                          calculateSquareSum(n)); # This Code is contributed by mits
// C# Program to find sum of// squares of Fibonacci numbers  using System;public class Improve {           // Function to calculate sum of    // squares of Fibonacci numbers    static int calculateSquareSum(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[0]) + (fibo[1] * fibo[1]);                // Add remaining terms        for (int i = 2; i <= n; i++) {            fibo[i] = fibo[i - 1] + fibo[i - 2];            sum += (fibo[i] * fibo[i]);        }                return sum;    }            // Driver code    public static void Main()    {           int n = 6;           Console.Write("Sum of squares of Fibonacci numbers is : " +                                calculateSquareSum(n));                }     }
<?php// PHP Program to find sum of// squares of Fibonacci numbers // Function to calculate sum of// squares of Fibonacci numbersfunction calculateSquareSum($n){    if ($n <= 0)        return 0;    $fibo[0] = 0;    $fibo[1] = 1;     // Initialize result    $sum = ($fibo[0] * $fibo[0]) +           ($fibo[1] * $fibo[1]);     // Add remaining terms    for ($i = 2; $i <= $n; $i++)    {        $fibo[$i] = $fibo[$i - 1] +                    $fibo[$i - 2];        $sum += ($fibo[$i] * $fibo[$i]);    }     return $sum;} // Driver Code$n = 6; echo "Sum of squares of Fibonacci numbers is : ",                          calculateSquareSum($n); // This Code is contributed by ajit?>
<script> // Javascript Program to find sum of// squares of Fibonacci numbers       // Function to calculate sum of    // squares of Fibonacci numbers    function calculateSquareSum(n)    {        if (n <= 0)            return 0;         var fibo = Array(n + 1).fill(0);        fibo[0] = 0;        fibo[1] = 1;         // Initialize result        var sum = (fibo[0] * fibo[0]) +                  (fibo[1] * fibo[1]);         // Add remaining terms        for (i = 2; i <= n; i++) {            fibo[i] = fibo[i - 1] + fibo[i - 2];            sum += (fibo[i] * fibo[i]);        }         return sum;    }     // Driver code             var n = 6;        document.write("Sum of squares of Fibonacci numbers is :"+ calculateSquareSum(n)); // This code contributed by gauravrajput1 </script>
Sum of squares of Fibonacci numbers is : 104
 
Method 2: We know that for i-th fibonacci number, 
fi+1 = fi + fi-1  for all i>0

Or, fi = fi+1 - fi-1 for all i>0
Or, fi2 = fifi+1 - fi-1fi
So for any n>0 we see, 
f02 + f12 + f22+.......+fn2 = f02 + ( f1f2– f0f1)+(f2f3 – f1f2 ) +.............+ (fnfn+1 – fn-1fn ) = fnfn+1 (Since f0 = 0)  
This identity also satisfies for n=0 ( For n=0, f02 = 0 = f0 f1 ) .Therefore, to find the sum, it is only needed to find fn and fn+1. To find fn in O(log n) time. Refer to Method 5 or method 6 of this article.Below is the implementation of the above approach:  
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find sum of squares of// Fibonacci numbers in O(Log n) time.#include <bits/stdc++.h>using namespace std;const int MAX = 1000; // Create an array for memoizationint 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];} // Function to calculate sum of// squares of Fibonacci numbersint calculateSumOfSquares(int n){    return fib(n) * fib(n + 1);} // Driver Codeint main(){    int n = 6;     cout << "Sum of Squares of Fibonacci numbers is : "         << calculateSumOfSquares(n) << endl;     return 0;}
// Java Program to find sum of squares of// Fibonacci numbers in O(Log n) time. class gfg {     static int[] f = new int[1000];// Create an array for memoization // Returns n'th Fibonacci number using table f[]    public 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];    } // Function to calculate sum of// squares of Fibonacci numbers    public static int calculateSumOfSquares(int n) {        return fib(n) * fib(n + 1);    }} // Driver Codeclass geek {     public static void main(String[] args) {        gfg g = new gfg();        int n = 6;        System.out.println("Sum of Squares of Fibonacci numbers is : "                + g.calculateSumOfSquares(n));    } }// This code is contributed by PrinciRaj1992
# Python3 program to find sum of squares# of Fibonacci numbers in O(Log n) time.MAX = 1000 # Create an array for memoizationf = [0 for i in range(MAX)] # Returns n'th Fibonacci number using# table f[]def fib(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]:        return f[n]     if n & 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:        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] # Function to calculate sum of# squares of Fibonacci numbersdef calculateSumOfSquares(n):     return fib(n) * fib(n + 1) # Driver Coden = 6print("Sum of Squares of "      "Fibonacci numbers is :",      calculateSumOfSquares(n)) # This code is contributed by Gaurav Kumar Tailor
// C# Program to find sum of squares of// Fibonacci numbers in O(Log n) time.using System;class gfg{ int []f = new int [1000];  // Create an array for memoization       // Returns n'th Fibonacci number using table f[]  public 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]; } // Function to calculate sum of// squares of Fibonacci numberspublic int calculateSumOfSquares(int n) {    return fib(n) * fib(n + 1); }} // Driver Codeclass geek{ public static int Main() {    gfg g = new gfg();    int n = 6;    Console.WriteLine( "Sum of Squares of Fibonacci numbers is : {0}", g.calculateSumOfSquares(n));    return 0; }     }
<?php// PHP Program to find sum of squares of// Fibonacci numbers in O(Log n) time. $MAX = 1000;global $f; // Create an array for memoization$f = array_fill(0, $MAX, 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);     $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];} // Function to calculate sum of// squares of Fibonacci numbersfunction calculateSumOfSquares( $n){    return fib($n) * fib($n + 1);} // Driver Code$n = 6; echo "Sum of Squares of Fibonacci numbers is : ";echo calculateSumOfSquares($n); // This code is contributed by Rajput-Ji?>
<script>    // Javascript Program to find sum of squares of    // Fibonacci numbers in O(Log n) time.         // Create an array for memoization    let f = new Array(1000);    f.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];        }          let 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];    }      // Function to calculate sum of    // squares of Fibonacci numbers    function calculateSumOfSquares(n) {        return fib(n) * fib(n + 1);    }         let n = 6;      document.write("Sum of Squares of Fibonacci numbers is : "         + calculateSumOfSquares(n)); </script>
Sum of Squares of Fibonacci numbers is : 104
 
ankthon
ukasp
jit_t
SoumikMondal
princiraj1992
Mithun Kumar
Rajput-Ji
gauravtailorthoi
GauravRajput1
suresh07
surindertarika1234
Fibonacci
series
series-sum
Technical Scripter 2018
C++ Programs
Mathematical
Mathematical
series
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Modulo Operator (%) in C/C++ with Examples