Find the sum of n terms of the series 1,8,27,64 ….
Given a series, the task is to find the sum of the below series up to n terms:
1, 8, 27, 64, …
Examples:
Input: N = 2 Output: 9 9 = (2*(2+1)/2)^2 Input: N = 4 Output: 100 100 = (4*(4+1)/2)^2
Approach: We can solve this problem using the following formula:
Sn = 1 + 8 + 27 + 64 + .........up to n terms
Sn = (n*(n+1)/2)^2Below is the implementation opf above approach:
C++
// C++ program to find the sum of n terms#include <bits/stdc++.h>using namespace std;// Function to calculate the sumint calculateSum(int n){ // Return total sum return pow(n * (n + 1) / 2, 2);}// Driver codeint main(){ int n = 4; cout << calculateSum(n); return 0;} |
Java
// Java program to find the sum of n termsimport java.io.*;class GFG {// Function to calculate the sumstatic int calculateSum(int n){ // Return total sum return (int)Math.pow(n * (n + 1) / 2, 2);}// Driver code public static void main (String[] args) { int n = 4; System.out.println( calculateSum(n)); }}// This code is contributed by inder_verma.. |
Python3
# Python3 program to find the# sum of n terms#Function to calculate the sumdef calculateSum(n): #return total sum return (n * (n + 1) / 2)**2 #Driver codeif __name__=='__main__': n = 4 print(calculateSum(n))#this code is contributed by Shashank_Sharma |
C#
// C# program to find the sum of n termsusing System;class GFG{// Function ot calculate the sumstatic int calculateSum(int n){ // Return total sum return (int)Math.Pow(n * (n + 1) / 2, 2);}// Driver codepublic static void Main (){ int n = 4; Console.WriteLine(calculateSum(n));}}// This code is contributed// by Akanksha Rai(Abby_akku) |
PHP
<?php// PHP program to find// the sum of n terms // Function to calculate the sumfunction calculateSum($n){ // Return total sum return pow($n * ($n + 1) / 2 , 2);} // Driver code$n = 4;echo calculateSum($n); // This code is contributed// by ANKITRAI1?> |
Javascript
<script>// javascript program to find the sum of n terms// Function to calculate the sumfunction calculateSum(n){ // Return total sum return parseInt(Math.pow(n * (n + 1) / 2, 2));}// Driver code var n = 4;document.write( calculateSum(n));// This code contributed by shikhasingrajput</script> |
Output:
100
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


