Open In App

Find the sum of N terms of the series 1, (2+3), (4+5+6), …..

Last Updated : 20 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a positive integer, N. Find the sum of the first N term of the series-

1, (2+3), (4+5+6),….,till N terms

Examples:

Input: N = 5

Output: 120

Input: N = 1

Output: 1

 

Approach: The sequence is formed by using the following pattern. For any value N-

SN = N * (N + 1) * (N2 + N + 2) / 8

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
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.


Output

120

Time Complexity: O(1), since there is no loop or recursion.
Auxiliary Space: O(1), since no extra space has been taken.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads