给定整数N。任务是找到高达给出一系列的N项之和:
3, -6, 12, -24, … upto N terms
例子:
Input : N = 5
Output : Sum = 33
Input : N = 20
Output : Sum = -1048575
通过观察给定的级数,可以看出每一项与前一项的比率为-2 。因此,给定的级数是GP(几何级数)级数。
您可以在此处了解有关GP系列的更多信息。
所以, 当r <0时。
在以上GP系列中,第一项i:e a = 3且公共比率i:e r =(-2) 。
所以, 。
因此, 。
下面是上述方法的实现:
C++
//C++ program to find sum upto N term of the series:
// 3, -6, 12, -24, .....
#include
#include
using namespace std;
//calculate sum upto N term of series
class gfg
{
public:
int Sum_upto_nth_Term(int n)
{
return (1 - pow(-2, n));
}
};
// Driver code
int main()
{
gfg g;
int N = 5;
cout<
Java
//Java program to find sum upto N term of the series:
// 3, -6, 12, -24, .....
import java.util.*;
//calculate sum upto N term of series
class solution
{
static int Sum_upto_nth_Term(int n)
{
return (1 -(int)Math.pow(-2, n));
}
// Driver code
public static void main (String arr[])
{
int N = 5;
System.out.println(Sum_upto_nth_Term(N));
}
}
Python
# Python program to find sum upto N term of the series:
# 3, -6, 12, -24, .....
# calculate sum upto N term of series
def Sum_upto_nth_Term(n):
return (1 - pow(-2, n))
# Driver code
N = 5
print(Sum_upto_nth_Term(N))
C#
// C# program to find sum upto
// N term of the series:
// 3, -6, 12, -24, .....
// calculate sum upto N term of series
class GFG
{
static int Sum_upto_nth_Term(int n)
{
return (1 -(int)System.Math.Pow(-2, n));
}
// Driver code
public static void Main()
{
int N = 5;
System.Console.WriteLine(Sum_upto_nth_Term(N));
}
}
// This Code is contributed by mits
PHP
Javascript
输出:
33