📜  求数列 1, (2+3), (4+5+6), .... 的 N 项之和

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

求数列 1, (2+3), (4+5+6), .... 的 N 项之和

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

例子

方法:使用以下模式形成序列。对于任何值 N-

下面是上述方法的实现:

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


Java
/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
 
    // Function to return sum of
    // N term of the series
    static int findSum(int N)
    {
 
        return N * (N + 1) * (N * N + N + 2) / 8;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 5;
 
        System.out.println(findSum(N));
    }
}
 
// This code is contributed by Potta Lokesh


Python3
# Python 3 program for the above approach
 
# Function to return sum of
# N term of the series
 
def findSum(N):
    return N * (N + 1) * (N * N + N + 2) // 8
 
 
# Driver Code
if __name__ == "__main__":
   
    # Value of N
    N = 5
    print(findSum(N))
 
# This code is contributed by Abhishek Thakur.


C#
/*package whatever //do not write package name here */
using System;
 
class GFG
{
 
  // Function to return sum of
  // N term of the series
  static int findSum(int N)
  {
 
    return N * (N + 1) * (N * N + N + 2) / 8;
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 5;
 
    Console.Write(findSum(N));
  }
}
 
// This code is contributed by Saurabh Jaiswal


Javascript
// Javascript program to implement
// the above approach
 
// Function to return sum of
// N term of the series
function findSum(N)
{
 
    return N
      * (N + 1)
      * (N * N + N + 2) / 8;
}
 
// Driver Code
let N = 5
document.write(findSum(N))
 
// This code is contributed by saurabh_jaiswal.



输出
120

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