# Sum of squares of Fibonacci numbers

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

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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++

 // C++ Program to find sum of // squares of Fibonacci numbers #include using namespace std;    // Function to calculate sum of // squares of Fibonacci numbers int 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 function int main() {     int n = 6;        cout << "Sum of squares of Fibonacci numbers is : "          << calculateSquareSum(n) << endl;        return 0; }

## Java

 // 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

 # Python3 Program to find sum of  # squares of Fibonacci numbers     # Function to calculate sum of  # squares of Fibonacci numbers  def 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 Code n = 6;     print("Sum of squares of Fibonacci numbers is :",                           calculateSquareSum(n));     # This Code is contributed by mits

## C#

 // 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



Output:

Sum of squares of Fibonacci numbers is : 104

Method 2: We know that for i-th fibonnacci 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++

 // C++ Program to find sum of squares of // Fibonacci numbers in O(Log n) time. #include 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]; }    // Function to calculate sum of // squares of Fibonacci numbers int calculateSumOfSquares(int n) {     return fib(n) * fib(n + 1); }    // Driver Code int main() {     int n = 6;        cout << "Sum of Squares of Fibonacci numbers is : "          << calculateSumOfSquares(n) << endl;        return 0; }

## Java

 // 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 Code  class 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

## C#

 // 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 numbers public int calculateSumOfSquares(int n)  {      return fib(n) * fib(n + 1);  } }    // Driver Code class 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



Output:

Sum of Squares of Fibonacci numbers is : 104

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.