Sum of Fibonacci Numbers with alternate negatives

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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-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 general term for the alternating Fibonacci Sum:

F1 – F2 + F3 -…….+ (-1)n+1 Fn = 1 + (-1)n+1Fn-1

So in order to find 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Alternating Fibonacci Sum upto 8 terms: -12


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.