给定下面给出的二次级数,任务是找到该级数的前n个项的和。
Sn = 3 + 7 + 13 + 21 + 31 + ….. + upto n terms
例子:
Input: N = 3
Output: 23
Input: N = 4
Output: 44
方法:
让系列表示为
Sn = 3 + 7 + 13 + ... + tn
在哪里
- S n表示直到n个项的序列之和。
- t n表示级数的第n个项。
现在,要表述系列,需要通过考虑系列中连续元素的差来形成元素。
Equation 1: Sn = 3 + 7 + 13 + 21 + 31 +…..+ tn-1 + tn
Equation 2: Sn = 0 + 3 + 7 + 13 + 21 + 31 + …… + tn-1 + tn
(writing the above series by shifting all elements to right by 1 position)
现在,从方程式1中减去方程式2,即(方程式1 –方程式2)
Sn – Sn = (3 – 0) + (7 – 3) + (13 – 7) + (31 – 21) + …… + (tn- tn-1) – tn
=> 0 = 3 + 4 + 6 + 8 + 10 + …… + (tn – tn-1) – tn
在上述系列中,撇开3个,从4到(tn – tn-1)的术语将构成AP
由于AP的n项之和的公式为:
Sn = n*(2*a + (n – 1)*d)/2
这意味着
In series: 4 + 6 + 8 + … + (tn – tn-1)
AP is formed with (n-1) terms.
因此,
Sum of this series: (n-1)*(2*4 + (n-2)*2)/2
因此,原始系列:
0 = 3 +(n-1)*(2 * 4 +(n-2)* 2)/ 2 – tn
其中tn = n ^ 2 + n + 1 ,这是第n个项。
所以,
Sum of first n terms of series will be:
tn = n^2 + n + 1
Sn = (n^2) + n + (1)
Sn = n*(n+1)*(n+2)/6 + n*(n+1)/2 + n
Sn = n*(n^2 + 3*n + 5)/3
下面是上述方法的实现:
C++
// C++ program to find sum of first n terms
#include
using namespace std;
int calculateSum(int n)
{
// Sum = n*(n^2 + 3*n + 5)/3
return n * (pow(n, 2) + 3 * n + 5) / 3;
}
int main()
{
// number of terms to be included in the sum
int n = 3;
// find the Sum
cout << "Sum = " << calculateSum(n);
return 0;
}
Java
// Java program to find sum of first n terms
import java.util.*;
class solution
{
//function to calculate sum of n terms of the series
static int calculateSum(int n)
{
// Sum = n*(n^2 + 3*n + 5)/3
return n * (int) (Math.pow(n, 2) + 3 * n + 5 )/ 3;
}
public static void main(String arr[])
{
// number of terms to be included in the sum
int n = 3;
// find the Sum
System.out.println("Sum = " +calculateSum(n));
}
}
Python3
# Python 3 program to find sum
# of first n terms
from math import pow
def calculateSum(n):
# Sum = n*(n^2 + 3*n + 5)/3
return n * (pow(n, 2) + 3 * n + 5) / 3
if __name__ == '__main__':
# number of terms to be included
# in the sum
n = 3
# find the Sum
print("Sum =", int(calculateSum(n)))
# This code is contributed by
# Sanjit_Prasad
C#
// C# program to find sum of first n terms
using System;
class gfg
{
public double calculateSum(int n)
{
// Sum = n*(n^2 + 3*n + 5)/3
return (n * (Math.Pow(n, 2) + 3 * n + 5) / 3);
}
}
//driver code
class geek
{
public static int Main()
{
gfg g = new gfg();
// number of terms to be included in the sum
int n = 3;
//find the Sum
Console.WriteLine( "Sum = {0}", g.calculateSum(n));
return 0;
}
}
PHP
Javascript
Sum = 23