Sum of Fibonacci Numbers with alternate negatives

06 May, 2021
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++
Java
Python 3
C#
PHP
Javascript
// 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 sumint 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 functionint main(){     // Get n    int n = 8;     // Find the alternating sum    cout << "Alternating Fibonacci Sum upto "         << n << " terms: "         << calculateAlternateSum(n) << endl;     return 0;}
// 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 Program to find alternate sum# of Fibonacci numbers # Computes value of first fibonacci numbers# and stores their alternate sumdef 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 functionif __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# Program to find alternate sum// of Fibonacci numbersusing System; class GFG{ // Computes value of first fibonacci numbers// and stores their alternate sumstatic 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 codepublic 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 Program to find alternate sum// of Fibonacci numbers // Computes value of first fibonacci// numbers and stores their alternate sumfunction 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 sumecho ("Alternating Fibonacci Sum upto ");echo $n ;echo " terms: ";echo (calculateAlternateSum($n)) ; // This code isw contributed// by Shivi_Aggarwal?>
<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
 
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-1Assuming 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++
Java
Python3
C#
Javascript
// 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 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];} // Computes value of Alternate  Fibonacci Sumint calculateAlternateSum(int n){    if (n % 2 == 0)        return (1 - fib(n - 1));    else        return (1 + fib(n - 1));} // Driver program to test above functionint main(){    // Get n    int n = 8;     // Find the alternating sum    cout << "Alternating Fibonacci Sum upto "         << n << " terms  : "         << calculateAlternateSum(n) << endl;     return 0;}
// 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 program to find alternative# Fibonacci Sum in O(Log n) time.MAX = 1000 # List for memorizationf = [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 Sumdef cal(n):         if(n % 2 == 0):        return(1 - fib(n - 1))    else:        return(1 + fib(n - 1))     # Driver Codeif(__name__=="__main__"):         n = 8    print("Alternating Fibonacci Sum upto",           n, "terms :", cal(n)) # This code is contributed by arjunsaini9081
// 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
<script> //Javascript implementation of the approachMAX = 1000; // Create an array for memoizationf = 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 Sumfunction calculateAlternateSum(n){    if (n % 2 == 0)        return (1 - fib(n - 1));    else        return (1 + fib(n - 1));}  // Get nvar n = 8;// Find the alternating sumdocument.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
 
ankthon
inderDuMCA
ukasp
Shivi_Aggarwal
princiraj1992
29AjayKumar
Shivam_k
arjunsaini9081
GauravRajput1
SoumikMondal
Fibonacci
series
series-sum
Technical Scripter 2018
Mathematical
Mathematical
series
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Merge two sorted arrays with O(1) extra space
Segment Tree | Set 1 (Sum of given range)
Fizz Buzz Implementation
Check if a number is Palindrome
Count ways to reach the n'th stair
Product of Array except itself
Find Union and Intersection of two unsorted arrays
Median of two sorted arrays of same size