📌  相关文章
📜  系列3、5、9、17、33…的前n个项的总和。

📅  最后修改于: 2021-04-29 01:31:40             🧑  作者: Mango

给定n,我们需要找到表示为Sn = 3 + 5 + 9 + 17 + 33…直至n的级数的前n个项之和

例子:

Input : 2
Output : 8
3 + 5 = 8

Input : 5
Output : 67
3 + 5 + 9 + 17 + 33 = 67

令,第n项由tn表示。
可以通过如下拆分每个术语来轻松解决此问题:

我们观察到第n个项可以用2和1的幂表示。
因此,前n个项的总和如下:

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


Java
// Java program to find
// sum of first n terms
import java.util.*;
  
class GFG 
{
static int calculateSum(int n)
{
    // Sn = n*(4*n*n + 6*n - 1)/3
    return ((int)Math.pow(2, n + 1) + 
                             n - 2);
}
  
// Driver Code
public static void main(String args[])
{
    // number of terms to 
    // be included in sum
    int n = 4;
  
    // find the Sn
    System.out.println("Sum = " + 
                calculateSum(n));
}
}
  
// This code is contributed 
// by Kirti_Mangal


Python
# Python program to find sum 
# of n terms of the series
def calculateSum(n):
  
    return (2**(n + 1) + n - 2)
  
# Driver Code
  
# number of terms for the sum
n = 4
  
# find the Sn
print("Sum =", calculateSum(n))
  
# This code is contributed 
# by Surendra_Gangwar


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


PHP


输出:
Sum = 34
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”