给定正整数N ,任务是找到序列1 –(1/2)+(1/3)–(1/4)+…的和。 (1 / N)使用递归。
例子:
Input: N = 3
Output: 0.8333333333333333
Explanation:
1 – (1/2) + (1/3) = 0.8333333333333333
Input: N = 4
Output: 0.5833333333333333
Explanation:
1- (1/2) + (1/3) – (1/4) = 0.5833333333333333
方法:想法是形成一个递归案例和一个基本案例,以便使用递归解决这个问题。所以:
- 基本情况:此问题的基本情况是当我们计算出总和直到分母中的N值。因此,当计数器变量“ i”达到值N时,我们将停止递归。
- 递归情况:此问题的递归情况是查找分母是偶数还是奇数。这是因为,显然,对于每个奇数,前一个符号是“ +”,对于每个偶数,前一个符号是“-”。因此,我们检查计数器变量是偶数还是奇数,并相应地增加或减少该值。然后,递归地调用该函数以获取值’i’的下一个值。
下面是上述方法的实现:
C++
// C++ program to find the value of
// the given series
#include
using namespace std;
// Recursive program to find the
// value of the given series
float sumOfSeries(int i, int n, float s)
{
// Base case
if (i > n )
return s;
// Recursive case
else
{
// If we are currently looking
// at the even number
if (i % 2 == 0)
s -= (float)1 / i;
// If we are currently looking
// at the odd number
else
s+= (float)1 / i;
return sumOfSeries(i + 1, n, s);
}
}
// Driver code
int main()
{
// cout<
Java
// Java program to find the value of
// the given series
import java.util.*;
class GFG{
// Recursive program to find the
// value of the given series
static float sumOfSeries(int i, int n, float s)
{
// Base case
if (i > n)
return s;
// Recursive case
else
{
// If we are currently looking
// at the even number
if (i % 2 == 0)
s -= (float)1 / i;
// If we are currently looking
// at the odd number
else
s += (float)1 / i;
return sumOfSeries(i + 1, n, s);
}
}
// Driver code
public static void main(String[] args)
{
float sum = sumOfSeries(1, 3, 0);
System.out.printf("%f", sum);
}
}
// This code is contributed by Amit Katiyar
Python3
# Python program to find the value of
# the given series
# Recursive program to find the
# value of the given series
def sumOfSeries(i, n, s) :
# Base case
if i>n :
return s
# Recursive case
else :
# If we are currently looking
# at the even number
if i % 2 == 0 :
s-= 1 / i
# If we are currently looking
# at the odd number
else :
s+= 1 / i
return sumOfSeries(i + 1, n, s)
# Driver code
if __name__ == "__main__":
print(sumOfSeries(1, 3, 0))
C#
// C# program to find the value of
// the given series
using System;
class GFG{
// Recursive program to find the
// value of the given series
static float sumOfSeries(int i, int n, float s)
{
// Base case
if (i > n )
return s;
// Recursive case
else
{
// If we are currently looking
// at the even number
if (i % 2 == 0)
s -= (float)1 / i;
// If we are currently looking
// at the odd number
else
s += (float)1 / i;
return sumOfSeries(i + 1, n, s);
}
}
// Driver code
public static void Main()
{
float sum = sumOfSeries(1, 3, 0);
Console.Write(sum);
}
}
// This code is contributed by Code_Mech
输出:
0.8333333333333333