📜  求系列 1, 4, 13, 40, 121, ... 的 N 项之和

📅  最后修改于: 2022-05-13 01:56:09.890000             🧑  作者: Mango

求系列 1, 4, 13, 40, 121, ... 的 N 项之和

给定一个正整数n 。求系列的前n 项之和:

例子:

方法:

该序列是通过使用以下模式形成的。对于任何值 N-

上述解决方案可以通过以下一系列步骤得出 -

插图:

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to return sum of
// first N term of the series
int findSum(int N)
{
    return (pow(3, N + 1) -
                3 - 2 * N) / 4;
}
 
// Driver Code
int main()
{
    int N = 5;
    cout << findSum(N);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
public class GFG
{
 
  // Function to return sum of
  // first N term of the series
  static int findSum(int N)
  {
    return (int)(Math.pow(3, N + 1) -
                 3 - 2 * N) / 4;
  }
 
  public static void main(String args[])
  {
    int N = 5;
    System.out.print(findSum(N));
  }
}
// This code is contributed by Samim Hossain Mondal.


Python3
# Python code for the above approach
 
# Function to return sum of
# first N term of the series
def findSum(N):
    return (3 ** (N + 1) - 3 - 2 * N) // 4;
 
# Driver Code
N = 5;
print(findSum(N));
 
# This code is contributed by Saurabh Jaiswal


C#
// C# program to implement
// the above approach
using System;
class GFG
{
 
// Function to return sum of
// first N term of the series
static int findSum(int N)
{
    return (int)(Math.Pow(3, N + 1) -
                3 - 2 * N) / 4;
}
 
  // Driver Code
  public static void Main()
  {
    int N = 5;
    Console.Write(findSum(N));
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript



输出
179

时间复杂度: O(1)

辅助空间: O(1)