Suma de números de Fibonacci con negativos alternos

Dado un entero positivo n, la tarea es encontrar el valor de F 1 – F 2 + F 3 -……….+ (-1) n+1 F n donde F i denota el i-ésimo número de Fibonacci.
Números de Fibonacci: Los números de Fibonacci son los números en la siguiente secuencia de enteros.
 

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ….

En términos matemáticos, la secuencia Fn de los números de Fibonacci está definida por la relación de recurrencia 
 

Fn = Fn-1 + Fn-2

con valores semilla F 0 = 0 y F 1 = 1.
Ejemplos 
 

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

Método 1: (Complejidad de tiempo O(n)) Este método incluye resolver el problema directamente encontrando todos los números de Fibonacci hasta n y sumando la suma alterna. Pero esto requerirá una complejidad de tiempo O(n).
A continuación se muestra la implementación del enfoque anterior: 
 

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>
Producción: 

Alternating Fibonacci Sum upto 8 terms: -12

 

Método 2: (O(log n) Complejidad) Este método involucra la siguiente observación para reducir la complejidad del tiempo:
 

  • Para n = 2, 
    F 1 – F 2 = 1 – 1 
    = 0 
    = 1 + (-1) 3 * F 1
  • Para n = 3, 
    F 1 – F 2 + F 3 
    = 1 – 1 + 2 
    = 2 
    = 1 + (-1) 4 * F 2
  • Para n = 4, 
    F 1 – F 2 + F 3 – F 4 
    = 1 – 1 + 2 – 3 
    = -1 
    = 1 + (-1) 5 * F 3
  • Para n = m, 
    F 1 – F 2 + F 3 -…….+ (-1) m+1 * F m-1 
    = 1 + (-1) m+1 F m-1
    Suponiendo que esto sea cierto. Ahora bien, si (n = m+1) también es cierto, significa que la suposición es correcta. De lo contrario, está mal.
  • Para n = m+1, 
    F 1 – F 2 + F 3 -…….+ (-1) m+1 * F m + (-1) m+2 * F m+1 
    = 1 + (-1) m+1 * F m-1 + (-1) m+2 * F m+1 
    = 1 + (-1) m+1 (F m-1 – F m+1
    = 1 + (-1) m +1 (-F m ) = 1 + (-1) m+2 (F m )
    lo cual es cierto según la suposición de n = m. 
     

De ahí el término general para la suma alterna de Fibonacci:
 

F 1 – F 2 + F 3 -…….+ (-1) n+1 F n = 1 + (-1) n+1 F n-1

Entonces, para encontrar una suma alternativa, solo se debe encontrar el n-ésimo término de Fibonacci, lo que se puede hacer en el tiempo O (log n) (consulte el Método 5 o 6 de este artículo).
A continuación se muestra la implementación del método 6 de esto: 
 

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>
Producción: 

Alternating Fibonacci Sum upto 8 terms: -12

 

Publicación traducida automáticamente

Artículo escrito por tufan_gupta2000 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *