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 by the recurrence relation
Fn = Fn-1 + Fn-2
with seed values F0 = 0 and F1 = 1.
Examples
Input: n = 5 Output: 4 Explanation: 1 - 1 + 2 - 3 + 5 = 4 Input: n = 8 Output: -12 Explanation: 1 - 1 + 2 - 3 + 5 - 8 + 13 - 21 = -12
Method 1: (O(n) time Complexity) This method includes solving the problem directly by finding all Fibonacci numbers till n and adding up the alternating sum. But this will require O(n) time complexity.
Below is the implementation of the above approach:
C++
// C++ Program to find alternate sum // of Fibonacci numbers #include <bits/stdc++.h> using namespace std; // Computes value of first fibonacci numbers // and stores their alternate sum int calculateAlternateSum( int n) { if (n <= 0) return 0; int fibo[n + 1]; fibo[0] = 0, fibo[1] = 1; // Initialize result int sum = pow (fibo[0], 2) + pow (fibo[1], 2); // Add remaining terms for ( int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum; } // Driver program to test above function int main() { // Get n int n = 8; // Find the alternating sum cout << "Alternating Fibonacci Sum upto " << n << " terms: " << calculateAlternateSum(n) << endl; return 0; } |
Java
// Java Program to find alternate sum // of Fibonacci numbers public class GFG { //Computes value of first fibonacci numbers // and stores their alternate sum static double calculateAlternateSum( int n) { if (n <= 0 ) return 0 ; int fibo[] = new int [n + 1 ]; fibo[ 0 ] = 0 ; fibo[ 1 ] = 1 ; // Initialize result double sum = Math.pow(fibo[ 0 ], 2 ) + Math.pow(fibo[ 1 ], 2 ); // Add remaining terms for ( int i = 2 ; i <= n; i++) { fibo[i] = fibo[i - 1 ] + fibo[i - 2 ]; // For even terms if (i % 2 == 0 ) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum; } // Driver code public static void main(String args[]) { // Get n int n = 8 ; // Find the alternating sum System.out.println( "Alternating Fibonacci Sum upto " + n + " terms: " + calculateAlternateSum(n)); } // This Code is contributed by ANKITRAI1 } |
Python 3
# Python 3 Program to find alternate sum # of Fibonacci numbers # Computes value of first fibonacci numbers # and stores their alternate sum def calculateAlternateSum(n): if (n < = 0 ): return 0 fibo = [ 0 ] * (n + 1 ) fibo[ 0 ] = 0 fibo[ 1 ] = 1 # Initialize result sum = pow (fibo[ 0 ], 2 ) + pow (fibo[ 1 ], 2 ) # Add remaining terms for i in range ( 2 , n + 1 ) : fibo[i] = fibo[i - 1 ] + fibo[i - 2 ] # For even terms if (i % 2 = = 0 ): sum - = fibo[i] # For odd terms else : sum + = fibo[i] # Return the alternating sum return sum # Driver program to test above function if __name__ = = "__main__" : # Get n n = 8 # Find the alternating sum print ( "Alternating Fibonacci Sum upto " , n , " terms: " , calculateAlternateSum(n)) # this code is contributed by # ChitraNayal |
C#
// C# Program to find alternate sum // of Fibonacci numbers using System; class GFG { // Computes value of first fibonacci numbers // and stores their alternate sum static double calculateAlternateSum( int n) { if (n <= 0) return 0; int []fibo = new int [n + 1]; fibo[0] = 0; fibo[1] = 1; // Initialize result double sum = Math.Pow(fibo[0], 2) + Math.Pow(fibo[1], 2); // Add remaining terms for ( int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum; } // Driver code public static void Main() { // Get n int n = 8; // Find the alternating sum Console.WriteLine( "Alternating Fibonacci Sum upto " + n + " terms: " + calculateAlternateSum(n)); } } // This code is contributed by inder_verma |
PHP
<?php // PHP Program to find alternate sum // of Fibonacci numbers // Computes value of first fibonacci // numbers and stores their alternate sum function calculateAlternateSum( $n ) { if ( $n <= 0) return 0; $fibo = array (); $fibo [0] = 0; $fibo [1] = 1; // Initialize result $sum = pow( $fibo [0], 2) + pow( $fibo [1], 2); // Add remaining terms for ( $i = 2; $i <= $n ; $i ++) { $fibo [ $i ] = $fibo [ $i - 1] + $fibo [ $i - 2]; // For even terms if ( $i % 2 == 0) $sum -= $fibo [ $i ]; // For odd terms else $sum += $fibo [ $i ]; } // Return the alternating sum return $sum ; } // Driver Code // Get n $n = 8; // Find the alternating sum echo ( "Alternating Fibonacci Sum upto " ); echo $n ; echo " terms: " ; echo (calculateAlternateSum( $n )) ; // This code isw contributed // by Shivi_Aggarwal ?> |
Javascript
<script> // Javascript Program to find alternate sum // of Fibonacci numbers // Computes value of first fibonacci numbers // and stores their alternate sum function calculateAlternateSum(n) { if (n <= 0) return 0; var fibo = Array(n + 1).fill(0); fibo[0] = 0; fibo[1] = 1; // Initialize result var sum = Math.pow(fibo[0], 2) + Math.pow(fibo[1], 2); // Add remaining terms for (i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum; } // Driver code // Get n var n = 8; // Find the alternating sum document.write( "Alternating Fibonacci Sum upto " + n + " terms: " + calculateAlternateSum(n) ); // This code contributed by gauravrajput1 </script> |
Alternating Fibonacci Sum upto 8 terms: -12
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: (O(log n) Complexity) This method involves the following observation to reduce the time complexity:
- For n = 2,
F1 – F2 = 1 – 1
= 0
= 1 + (-1)3 * F1 - For n = 3,
F1 – F2 + F3
= 1 – 1 + 2
= 2
= 1 + (-1)4 * F2 - For n = 4,
F1 – F2 + F3 – F4
= 1 – 1 + 2 – 3
= -1
= 1 + (-1)5 * F3 - For n = m,
F1 – F2 + F3 -…….+ (-1)m+1 * Fm-1
= 1 + (-1)m+1Fm-1
Assuming this to be true. Now if (n = m+1) is also true, it means that the assumption is correct. Otherwise, it is wrong. - For n = m+1,
F1 – F2 + F3 -…….+ (-1)m+1 * Fm + (-1)m+2 * Fm+1
= 1 + (-1)m+1 * Fm-1 + (-1)m+2 * Fm+1
= 1 + (-1)m+1(Fm-1 – Fm+1)
= 1 + (-1)m+1(-Fm) = 1 + (-1)m+2(Fm)
which is true as per the assumption for n = m.
Hence the general term for the alternating Fibonacci Sum:
F1 – F2 + F3 -…….+ (-1)n+1 Fn = 1 + (-1)n+1Fn-1
So in order to find an alternate sum, only the n-th Fibonacci term is to be found, which can be done in O(log n) time( Refer to Method 5 or 6 of this article.)
Below is the implementation of method 6 of this:
C++
// C++ Program to find alternate Fibonacci Sum 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 Alternate Fibonacci Sum int calculateAlternateSum( int n) { if (n % 2 == 0) return (1 - fib(n - 1)); else return (1 + fib(n - 1)); } // Driver program to test above function int main() { // Get n int n = 8; // Find the alternating sum cout << "Alternating Fibonacci Sum upto " << n << " terms : " << calculateAlternateSum(n) << endl; return 0; } |
Java
// Java Program to find alternate // Fibonacci Sum in O(Log n) time. class GFG { static final 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 % 2 == 1 ) ? (n + 1 ) / 2 : n / 2 ; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n % 2 == 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 Alternate Fibonacci Sum static int calculateAlternateSum( int n) { if (n % 2 == 0 ) { return ( 1 - fib(n - 1 )); } else { return ( 1 + fib(n - 1 )); } } // Driver program to test above function public static void main(String[] args) { // Get n int n = 8 ; // Find the alternating sum System.out.println( "Alternating Fibonacci Sum upto " + n + " terms : " + calculateAlternateSum(n)); } } // This code is contributed by PrinciRaj1992 |
Python3
# Python3 program to find alternative # Fibonacci Sum in O(Log n) time. MAX = 1000 # List for memorization f = [ 0 ] * 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 ): f[n] = 1 return (f[n]) # 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]) # Computes value of Alternate Fibonacci Sum def cal(n): if (n % 2 = = 0 ): return ( 1 - fib(n - 1 )) else : return ( 1 + fib(n - 1 )) # Driver Code if (__name__ = = "__main__" ): n = 8 print ( "Alternating Fibonacci Sum upto" , n, "terms :" , cal(n)) # This code is contributed by arjunsaini9081 |
C#
// C# Program to find alternate // Fibonacci Sum in O(Log n) time. using System; class GFG { static readonly 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 % 2 == 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n % 2 == 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 Alternate Fibonacci Sum static int calculateAlternateSum( int n) { if (n % 2 == 0) { return (1 - fib(n - 1)); } else { return (1 + fib(n - 1)); } } // Driver code public static void Main() { // Get n int n = 8; // Find the alternating sum Console.WriteLine( "Alternating Fibonacci Sum upto " + n + " terms : " + calculateAlternateSum(n)); } } // This code is contributed by 29AjayKumar |
Javascript
<script> //Javascript implementation of the approach MAX = 1000; // Create an array for memoization f = new Array(MAX); 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]) return f[n]; var 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 Alternate Fibonacci Sum function calculateAlternateSum(n) { if (n % 2 == 0) return (1 - fib(n - 1)); else return (1 + fib(n - 1)); } // Get n var n = 8; // Find the alternating sum document.write( "Alternating Fibonacci Sum upto " + n + " terms : " + calculateAlternateSum(n) + "<br>" ); getElement(a, n, S); // This code is contributed by SoumikMondal </script> |
Alternating Fibonacci Sum upto 8 terms: -12
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!