📜  带有负数的斐波纳契数之和

📅  最后修改于: 2021-04-29 01:39:16             🧑  作者: Mango

给定一个正整数n,任务是找到F 1 – F 2 + F 3- ………。+(-1) n + 1 F n的值,其中F i表示第i个斐波那契数。
斐波那契数字:斐波那契数字是以下整数序列中的数字。

用数学术语来说,斐波纳契数的序列Fn由递归关系定义

Fn = Fn-1 + Fn-2

种子值F 0 = 0和F 1 = 1。
例子

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

方法1:(O(n)时间复杂度)该方法包括通过找到直到n的所有斐波那契数并直接求和,来直接解决问题。但这将需要O(n)时间复杂度。

下面是上述方法的实现:

C++
// C++ Program to find alternate sum
// of Fibonacci numbers
  
#include 
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


C++
// C++ Program to find alternate  Fibonacci Sum in
// O(Log n) time.
  
#include 
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


输出:
Alternating Fibonacci Sum upto 8 terms: -12

方法2:(O(log n)复杂度)此方法涉及以下观察以减少时间复杂度:

  • 对于n = 2
    F 1 – F 2 = 1 – 1
    = 0
    = 1 +(-1) 3 * F 1
  • 对于n = 3,
    F 1 – F 2 + F 3
    = 1 – 1 + 2
    = 2
    = 1 +(-1) 4 * F 2
  • 对于n = 4,
    F 1 – F 2 + F 3 – F 4
    = 1 – 1 + 2 – 3
    = -1
    = 1 +(-1) 5 * F 3
  • 对于n = m,
    F 1 – F 2 + F 3- ……。+(-1) m + 1 * F m-1
    = 1 +(-1) m + 1 F m-1
    假设这是真的。现在,如果(n = m + 1)也为真,则意味着该假设是正确的。否则是错误的。
  • 对于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 )
    根据n = m的假设,这是正确的。

因此,交替斐波那契和的总称:

因此,为了找到替代总和,只能找到第n个斐波纳契项,这可以在O(log n)时间中完成(请参阅本文的方法5或6)。

下面是此方法6的实现:

C++

// C++ Program to find alternate  Fibonacci Sum in
// O(Log n) time.
  
#include 
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
输出:
Alternating Fibonacci Sum upto 8 terms: -12