📌  相关文章
📜  求系列 1 的 N 项之和, (1+4) , (1+4+4^2), (1+4+4^2+4^3), .....

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

求系列 1 的 N 项之和, (1+4) , (1+4+4^2), (1+4+4^2+4^3), .....

给定一个正整数N 。找到系列的前 N 项的总和-

例子:

方法:

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

推导:

以下一系列步骤可用于推导公式以找到 N 项的总和 -

插图:

下面是上述方法的实现:

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


Java
// Java code for the above approach
import java.util.*;
 
class GFG{
 
  // Function to calculate the sum
  // of first N term
  static int calcSum(int n)
  {
    int a = (int)Math.pow(4, n);
    return (4 * (a - 1) - 3 * n) / 9;
  }
 
 
  // Driver Code
  public static void main(String[] args)
  {
    // Value of N
    int N = 3;
 
    // Function call to calculate
    // sum of the series
    System.out.print(calcSum(N));
  }
}
 
// This code is contributed by code_hunt.


Python3
# Python 3 program for the above approach
 
# Function to calculate the sum
# of first N term
def calcSum(n):
    a = pow(4, n)
    return (4 * (a - 1) - 3 * n) / 9
 
 
# Driver Code
if __name__ == "__main__":
 
    # Value of N
    N = 3
     
    # Function call to calculate
    # sum of the series
    print(calcSum(N))
 
# This code is contributed by Abhishek Thakur.


C#
// C# code for the above approach
using System;
 
class GFG{
 
  // Function to calculate the sum
  // of first N term
  static int calcSum(int n)
  {
    int a = (int)Math.Pow(4, n);
    return (4 * (a - 1) - 3 * n) / 9;
  }
 
 
  // Driver Code
  public static void Main()
  {
    // Value of N
    int N = 3;
 
    // Function call to calculate
    // sum of the series
    Console.Write(calcSum(N));
  }
}
 
// This code is contributed by gfgking


Javascript


输出
27

时间复杂度: O(1)
辅助空间: O(1)