📌  相关文章
📜  给定级数3、6、11,…的前n个项的总和。

📅  最后修改于: 2021-05-06 20:55:44             🧑  作者: Mango

给定一个序列和一个数字n,任务是找到其前n个项的总和。以下是系列:

例子:

Input: N = 2
Output: 9
The sum of first 2 terms of Series is
3 + 6 = 9

Input: N = 3
Output: 20
The sum of first 3 terms of Series is
3 + 6 + 11 = 20

方法:通过观察该系列的第n个项,可以轻松解决此问题:

我们观察到Sn是两个序列的AP和GP
众所周知,AP的前n个项之和为

    $$S_n=\frac{n}{2} \left(2 \times a1+(n-1) \times d\right)$$

GP的前n个项之和也由下式给出

    $$Sn=a2 \times \left(\frac{r^n-1}{r-1}\right)$$

因此,总和由AP和GP的总和给出。

    $$Total=\frac{n}{2} \left(2 \times a1+(n-1) \times d\right) +a2 \times \left(\frac{r^n-1}{r-1}\right)$$

下面是上述方法的实现。

C++
// C++ program to find sum of first n terms
#include 
using namespace std;
 
// Function to calculate the sum
int calculateSum(int n)
{
    // starting number
    int a1 = 1, a2 = 2;
 
    // Common Ratio
    int r = 2;
 
    // Common difference
    int d = 1;
 
    return (n) * (2 * a1 + (n - 1) * d) / 2 + a2
               * (pow(r, n) - 1) / (r - 1);
}
 
// Driver code
int main()
{
 
    // N th term to be find
    int n = 5;
 
    // 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)
{
    // starting number
    int a1 = 1, a2 = 2;
 
    // Common Ratio
    int r = 2;
 
    // Common difference
    int d = 1;
 
    return (n) * (2 * a1 + (n - 1) * d) / 2 + a2
            * (int)(Math.pow(r, n) - 1) / (r - 1);
}
 
// Driver code
    public static void main (String[] args) {
        // N th term to be find
    int n = 5;
 
    // find the Sn
    System.out.print( "Sum = " + calculateSum(n));
    }
}
// This code is contributed by inder_verma.


Python3
# Python3 program to find
# sum of first n terms
def calculateSum(n):
    # First term of AP
    a1 = 1;
     
    # First term of GP
    a2 = 2;
     
    # common ratio of GP
    r = 2;
     
    # common difference Of AP
    d = 1;
    return ((n) * (2 * a1 + (n - 1) * d) /
                   2 + a2 * (pow(r, n) - 1) /
                  (r - 1));
 
# Driver Code
 
# no. of the terms
# for the sum
n = 5;
 
# Find the Sn
print ("Sum =", int(calculateSum(n)))
 
# This code is contributed
# by Surendra_Gangwar


C#
// C# program to find sum
// of first n terms
using System;
 
class GFG
{
 
// Function to calculate the sum
static int calculateSum(int n)
{
    // starting number
    int a1 = 1, a2 = 2;
 
    // Common Ratio
    int r = 2;
 
    // Common difference
    int d = 1;
 
    return (n) * (2 * a1 + (n - 1) * d) / 2 + a2 *
             (int)(Math.Pow(r, n) - 1) / (r - 1);
}
 
// Driver code
public static void Main ()
{
    // N th term to be find
    int n = 5;
     
    // find the Sn
    Console.WriteLine("Sum = " + calculateSum(n));
}
}
 
// This code is contributed
// by inder_verma


PHP


Javascript


输出:
Sum = 77