Sum of Fibonacci Numbers with alternate negatives
Last Updated :
25 Aug, 2022
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>
Output: 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>
Output: Alternating Fibonacci Sum upto 8 terms: -12
Similar Reads
How to check if a given number is Fibonacci number? Given a number ânâ, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .. Examples :Input : 8Output : YesInput : 34Output : YesInput : 41Output : NoApproach 1:A simple way is to generate Fibonacci numbers until the generated number
15 min read
Nth Fibonacci Number Given a positive integer n, the task is to find the nth Fibonacci number.The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1. The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21Example:Input:
15+ min read
C++ Program For Fibonacci Numbers The Fibonacci series is the sequence where each number is the sum of the previous two numbers. The first two numbers of the Fibonacci series are 0 and 1, and they are used to generate the entire series.Examples:Input: 5Output: 5Explanation: As 5 is the 5th Fibonacci number of series 0, 1, 1, 2, 3, 5
5 min read
Python Program for n-th Fibonacci number In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2With seed values F0 = 0 and F1 = 1.Table of ContentPython Program for n-th Fibonacci number Using Formula Python Program for n-th Fibonacci number Using RecursionPython Program for n-th
6 min read
Interesting Programming facts about Fibonacci numbers We know Fibonacci number, Fn = Fn-1 + Fn-2. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, .... . Here are some interesting facts about Fibonacci number : 1. Pattern in Last digits of Fibonacci numbers : Last digits of first few Fibonacci Numbers ar
15+ min read
Find nth Fibonacci number using Golden ratio Fibonacci series = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ........Different methods to find nth Fibonacci number are already discussed. Another simple way of finding nth Fibonacci number is using golden ratio as Fibonacci numbers maintain approximate golden ratio till infinite. Golden ratio: \varphi ={\fr
6 min read
Fast Doubling method to find the Nth Fibonacci number Given an integer N, the task is to find the N-th Fibonacci numbers.Examples: Input: N = 3 Output: 2 Explanation: F(1) = 1, F(2) = 1 F(3) = F(1) + F(2) = 2 Input: N = 6 Output: 8 Approach: The Matrix Exponentiation Method is already discussed before. The Doubling Method can be seen as an improvement
14 min read
Tail Recursion for Fibonacci Write a tail recursive function for calculating the n-th Fibonacci number. Examples : Input : n = 4 Output : fib(4) = 3 Input : n = 9 Output : fib(9) = 34 Prerequisites : Tail Recursion, Fibonacci numbersA recursive function is tail recursive when the recursive call is the last thing executed by the
4 min read
Sum of Fibonacci Numbers Given a number positive number n, find value of f0 + f1 + f2 + .... + fn where fi indicates i'th Fibonacci number. Remember that f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ... Examples : Input : n = 3Output : 4Explanation : 0 + 1 + 1 + 2 = 4Input : n = 4Output : 7Explanation : 0 + 1 + 1 + 2 + 3
9 min read
Fibonacci Series
Program to Print Fibonacci SeriesEver wondered about the cool math behind the Fibonacci series? This simple pattern has a remarkable presence in nature, from the arrangement of leaves on plants to the spirals of seashells. We're diving into this Fibonacci Series sequence. It's not just math, it's in art, nature, and more! Let's dis
8 min read
Program to Print Fibonacci Series in JavaThe Fibonacci series is a series of elements where the previous two elements are added to generate the next term. It starts with 0 and 1, for example, 0, 1, 1, 2, 3, and so on. We can mathematically represent it in the form of a function to generate the n'th Fibonacci number because it follows a con
5 min read
Print the Fibonacci sequence - PythonTo print the Fibonacci sequence in Python, we need to generate a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The Fibonacci sequence follows a specific pattern that begins with 0 and 1, and every subsequent number is the sum of the two previous num
5 min read
C Program to Print Fibonacci SeriesThe Fibonacci series is the sequence where each number is the sum of the previous two numbers of the sequence. The first two numbers are 0 and 1 which are used to generate the whole series.ExampleInput: n = 5Output: 0 1 1 2 3Explanation: The first 5 terms of the Fibonacci series are 0, 1, 1, 2, 3.In
4 min read
JavaScript Program to print Fibonacci SeriesThe Fibonacci sequence is the integer sequence where the first two terms are 0 and 1. After that, the next term is defined as the sum of the previous two terms. The recurrence relation defines the sequence Fn of Fibonacci numbers:Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1Examples:Input : 5
4 min read
Length of longest subsequence of Fibonacci Numbers in an ArrayGiven an array arr containing non-negative integers, the task is to print the length of the longest subsequence of Fibonacci numbers in this array.Examples: Input: arr[] = { 3, 4, 11, 2, 9, 21 } Output: 3 Here, the subsequence is {3, 2, 21} and hence the answer is 3.Input: arr[] = { 6, 4, 10, 13, 9,
5 min read
Last digit of sum of numbers in the given range in the Fibonacci seriesGiven two non-negative integers M, N which signifies the range [M, N] where M ? N, the task is to find the last digit of the sum of FM + FM+1... + FN where FK is the Kth Fibonacci number in the Fibonacci series. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... Examples: Input: M = 3, N = 9 Output:
5 min read
K- Fibonacci seriesGiven integers 'K' and 'N', the task is to find the Nth term of the K-Fibonacci series. In K - Fibonacci series, the first 'K' terms will be '1' and after that every ith term of the series will be the sum of previous 'K' elements in the same series. Examples: Input: N = 4, K = 2 Output: 3 The K-Fibo
7 min read
Fibonacci Series in BashPrerequisite: Fibonacci Series Write a program to print the Fibonacci sequence up to nth digit using Bash. Examples: Input : 5 Output : Fibonacci Series is : 0 1 1 2 3 Input :4 Output : Fibonacci Series is : 0 1 1 2 The Fibonacci numbers are the numbers in the following integer sequence . 0, 1, 1, 2
1 min read
R Program to Print the Fibonacci SequenceThe Fibonacci sequence is a series of numbers in which each number (known as a Fibonacci number) is the sum of the two preceding ones. The sequence starts with 0 and 1, and then each subsequent number is the sum of the two previous numbers. The Fibonacci sequence has many applications in various fie
2 min read