📜  使用递归找到序列的几何和

📅  最后修改于: 2021-04-27 21:01:14             🧑  作者: Mango

给定一个整数N,我们需要使用递归找到以下系列的几何和。

例子:

Input N = 5 
Output: 1.49794

Input: N = 7
Output: 1.49977

方法:

在上述问题中,要求我们使用递归。我们将计算最后一项,并每次对其余n-1个项调用递归。返回的最终总和就是结果。

下面是上述方法的实现:

C++
// CPP implementation to Find the
// geometric sum of the series using recursion
  
#include 
using namespace std;
  
// function to find the sum of given series
double sum(int n)
{
    // base case
    if (n == 0)
        return 1;
  
    // calculate the sum each time
    double ans = 1 / (double)pow(3, n) + sum(n - 1);
  
    // return final answer
    return ans;
}
  
// Driver code
int main()
{
  
    // integer initialisation
    int n = 5;
  
    cout << sum(n) << endl;
  
    return 0;
}


Java
// JAVA implementation to Find the
// geometric sum of the series using recursion
  
import java.util.*;
  
class GFG {
  
    static double sum(int n)
    {
        // base case
        if (n == 0)
            return 1;
  
        // calculate the sum each time
        double ans = 1 / (double)Math.pow(3, n) + sum(n - 1);
  
        // return final answer
        return ans;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        // integer initialisation
        int n = 5;
  
        // print result
        System.out.println(sum(n));
    }
}


Python3
# CPP implementation to Find the 
# geometric sum of the series using recursion
  
  
def sum(n):
      
    # base case 
    if n == 0:
        return 1
      
    # calculate the sum each time
    # and return final answer
    return 1 / pow(3, n) + sum(n-1)
  
n = 5;
  
print(sum(n));


C#
// C# implementation to Find the
// geometric sum of the series using recursion
  
using System;
  
class GFG {
  
    static double sum(int n)
    {
        // base case
        if (n == 0)
            return 1;
  
        // calculate the sum each time
        double ans = 1 / (double)Math.Pow(3, n) + sum(n - 1);
  
        // return final answer
        return ans;
    }
  
    // Driver code
    static public void Main()
    {
        int n = 5;
  
        Console.WriteLine(sum(n));
    }
}


输出:
1.49794