Skip to main content

Sum of First n Terms

Problem​

Given an integer n, calculate the sum of series 13+23+33+43+…1^3 + 2^3 + 3^3 + 4^3 + … till n-th term.

Examples:​

Example 1:

Input:
n=5
Output:
225
Explanation:
1^3+2^3+3^3+4^3+5^3=225

Example 2:

Input:
n=7
Output:
784
Explanation:
1^3+2^3+3^3+4^3+5^3+6^3+7^3=784

Your task:​

You don't need to read input or print anything. Your task is to complete the function sumOfSeries() which takes the integer n as a parameter and returns the sum of the cubes of the first n natural numbers.

  • Expected Time Complexity: O(1)O(1)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1<=n<=500001<=n<=50000

Solution​

Python​

def sumOfSeries(self,n):
sum_cubes = (n * (n + 1) // 2) ** 2
return sum_cubes

Java​

long sumOfSeries(long n) {
long sum_cubes = (n * (n + 1) / 2) * (n * (n + 1) / 2);
return sum_cubes;
}

C++​

long long sumOfSeries(long long n) {
long long sum_cubes = (n * (n + 1) / 2) * (n * (n + 1) / 2);
return sum_cubes;
}

C​

long long sumOfSeries(long long n) {
long long sum_cubes = (n * (n + 1) / 2) * (n * (n + 1) / 2);
return sum_cubes;
}
  • Time Complexity: O(1)O(1)
  • Auxiliary Space: O(1)O(1)