![]() |
VOOZH | about |
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:
Sum of squares of Fibonacci numbers is : 104
Time Complexity: O(n)
Auxiliary Space: O(n)
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:
Sum of Squares of Fibonacci numbers is : 104
Time Complexity: O(logn)
Auxiliary Space: O(n)