Sum of First n Terms
Problem​
Given an integer n, calculate the sum of series 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:
- Expected Auxiliary Space:
Constraints:​
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:
- Auxiliary Space: