📌  相关文章
📜  5,12、23、38…系列的前N个项的总和。

📅  最后修改于: 2021-05-06 08:50:34             🧑  作者: Mango

给定数字N,任务是找到以下系列的前N个项的总和:

例子:

Input: N = 2
Output: 17
5 + 12
= 17

Input: N = 4 
Output: 80
5 + 12 + 23 + 38
= 78

方法:让第n个项用tn表示。
借助这些类型系列的通用公式,可以轻松解决此问题,
上面给出的级数是二次级数。它们之所以特别,是因为该系列的连续项之差将在算术级数中进行。
通用公式由下式给出:

General Formula = a*(n^2) + b*n + c

现在,通过将系列的前三个项放在通用公式中,我们可以获得a,b和c的值。

Sn = 5 + 12 + 30 + 68 + ......
tn = 2 * (n^2) + n + 2
Sn = 2 * (n * (n+1) * (2 * n+1)/6) + n * (n+1)/2 + 2 * (n)

下面是上述方法的实现:

C++
// C++ program to find sum of first n terms
#include 
using namespace std;
 
// Function to calculate the sum
int calculateSum(int n)
{
 
    return 2 * (n * (n + 1) * (2 * n + 1) / 6)
               + n * (n + 1) / 2 + 2 * (n);
}
 
// Driver code
int main()
{
    // number of terms to be included in sum
    int n = 3;
 
    // find the Sn
    cout << "Sum = " << calculateSum(n);
 
    return 0;
}


Java
// Java program to find sum of first n terms
 
import java.io.*;
 
class GFG {
 
// Function to calculate the sum
 static int calculateSum(int n)
{
 
    return 2 * (n * (n + 1) * (2 * n + 1) / 6)
            + n * (n + 1) / 2 + 2 * (n);
}
 
// Driver code
 
    public static void main (String[] args) {
        // number of terms to be included in sum
    int n = 3;
 
    // find the Sn
    System.out.print( "Sum = " + calculateSum(n));
    }
}
// This code is contributed
// by  anuj_67..


Python 3
# Python program to find
# sum of first n terms
 
# Function to calculate the sum
def calculateSum(n) :
 
    return (2 * (n * (n + 1) *
           (2 * n + 1) // 6) + n *
           (n + 1) // 2 + 2 * (n))
         
# Driver code    
if __name__ == "__main__" :
 
    # number of terms to be
    # included in sum
    n = 3
 
    # find the Sn
    print("Sum =",calculateSum(n))
 
# This code is contributed by ANKITRAI1


C#
// C# program to find sum
// of first n terms
using System;
 
class GFG
{
 
// Function to calculate the sum
static int calculateSum(int n)
{
 
    return 2 * (n * (n + 1) * (2 * n + 1) / 6) +
                n * (n + 1) / 2 + 2 * (n);
}
 
// Driver code
public static void Main ()
{
    // number of terms to be
    // included in sum
    int n = 3;
     
    // find the Sn
    Console.WriteLine("Sum = " + calculateSum(n));
}
}
 
// This code is contributed
// by Shashank


PHP


Javascript


输出:
Sum = 40