📌  相关文章
📜  二次序列3 + 7 + 13 +…的前N个项之和

📅  最后修改于: 2021-05-04 18:49:10             🧑  作者: Mango

给定下面给出的二次级数,任务是找到该级数的前n个项的和。

例子:

Input: N = 3
Output: 23

Input: N = 4
Output: 44

方法:
让系列表示为

Sn = 3 + 7 + 13 + ... + tn

在哪里

  • S n表示直到n个项的序列之和。
  • t n表示级数的第n个项。

现在,要表述系列,需要通过考虑系列中连续元素的差来形成元素。

现在,从方程式1中减去方程式2,即(方程式1 –方程式2)

在上述系列中,撇开3个,从4到(tn – tn-1)的术语将构成AP
由于AP的n项之和的公式为:

这意味着

因此,

因此,原始系列:
0 = 3 +(n-1)*(2 * 4 +(n-2)* 2)/ 2 – tn
其中tn = n ^ 2 + n + 1 ,这是第n个项。
所以,

下面是上述方法的实现:

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